如何将后端返回的JSON响应解析为目标数组?
Great question! The JSON response you're getting is already in exactly the structure you need—an array of arrays. The main task is just converting the raw JSON string (if that's how you receive it from the backend) into a native array/list in your programming language of choice. Here's how to do it in the most common languages:
JavaScript Solution
If you're working in JavaScript (frontend or Node.js), here's how to handle it:
Case 1: You receive the JSON as a raw string
Use JSON.parse() to convert the string into a native JavaScript array:
// Full JSON string from your backend const jsonString = '[["Bondi Beach",-33.890542,151.274856,4],["Coogee Beach",-33.923036,151.259052,5],["Cronulla Beach",-34.028249,151.157507,3],["Manly Beach",-33.80010128657071,151.28747820854187,2],["Maroubra Beach",-33.950198,151.259302,1]]'; const parsedArray = JSON.parse(jsonString); console.log(parsedArray); // Output matches your desired structure exactly: // [ // ['Bondi Beach', -33.890542, 151.274856, 4], // ['Coogee Beach', -33.923036, 151.259052, 5], // ... // ]
Case 2: Fetching directly with the fetch API
The response.json() method automatically parses the JSON into an array:
fetch('/your-backend-endpoint') .then(response => response.json()) .then(data => { // data is already the parsed array of arrays console.log(data); }) .catch(error => console.error('Error fetching data:', error));
Case 3: Using Axios
Axios handles parsing automatically—access the data via response.data:
axios.get('/your-backend-endpoint') .then(response => { const parsedArray = response.data; console.log(parsedArray); }) .catch(error => console.error('Error:', error));
Python Solution
For Python backend processing, use the built-in json module:
import json # JSON string from your backend json_string = '[["Bondi Beach",-33.890542,151.274856,4],["Coogee Beach",-33.923036,151.259052,5],["Cronulla Beach",-34.028249,151.157507,3],["Manly Beach",-33.80010128657071,151.28747820854187,2],["Maroubra Beach",-33.950198,151.259302,1]]' parsed_list = json.loads(json_string) print(parsed_list) // Outputs the list of lists you need: // [ // ['Bondi Beach', -33.890542, 151.274856, 4], // ['Coogee Beach', -33.923036, 151.259052, 5], // ... // ]
Note on the Ellipsis
The ... in your desired output looks like display truncation for the long floating-point number in the Manly Beach entry. If you want to explicitly shorten these values (e.g., to 6 decimal places), here's a quick example:
JavaScript Truncation:
const truncatedArray = parsedArray.map(item => [ item[0], parseFloat(item[1].toFixed(6)), parseFloat(item[2].toFixed(6)), item[3] ]);
Python Truncation:
truncated_list = [ [item[0], round(item[1], 6), round(item[2], 6), item[3]] for item in parsed_list ]
内容的提问来源于stack exchange,提问作者Spacex

