如何提取Google Distance Matrix API JSON结果中distance的value并转为字符串变量
Got it, let's break this down step by step. Assuming you have the JSON response from the Google Distance Matrix API, here's how you can extract that distance.value (7593) and save it as a string variable in two common programming languages:
Python Implementation
- First, let's use a simplified version of the typical API response as an example:
{ "rows": [ { "elements": [ { "distance": { "text": "7.6 km", "value": 7593 }, "duration": {} } ] } ] }
- Here's the code to parse and extract the value:
import json # Replace this with your actual API response string api_response = ''' { "rows": [ { "elements": [ { "distance": { "text": "7.6 km", "value": 7593 } } ] } ] } ''' # Parse the JSON string into a Python dictionary response_data = json.loads(api_response) # Navigate the nested structure to get the distance value distance_value = response_data['rows'][0]['elements'][0]['distance']['value'] # Convert to string and store in a variable distance_str = str(distance_value) # Verify the result (optional) print(distance_str) # Output: "7593"
- Pro tip: Add
try-exceptblocks to handle cases where the response structure might be missing fields (e.g., if the API returns an error), to avoid unexpectedKeyErrorcrashes.
JavaScript Implementation
This works for both browser-based code and Node.js:
- Sample API response object:
{ "rows": [ { "elements": [ { "distance": { "text": "7.6 km", "value": 7593 } } ] } ] }
- Code example:
// If you're fetching via API, first parse the response (e.g., with fetch) // fetch('your-api-url') // .then(res => res.json()) // .then(apiResponse => { // // extract value here // }); // For this example, we'll use a hardcoded response object const apiResponse = { "rows": [ { "elements": [ { "distance": { "text": "7.6 km", "value": 7593 } } ] } ] }; // Extract the distance value (use optional chaining ?. to avoid errors if fields are missing) const distanceValue = apiResponse?.rows[0]?.elements[0]?.distance?.value; // Convert to string and store in a variable const distanceStr = distanceValue?.toString() || ""; // Check the result console.log(distanceStr); // Output: "7593"
- Pro tip: The optional chaining operator (
?.) is super useful here—it prevents runtime errors if any nested property is missing (like if the API returns no elements for a route).
内容的提问来源于stack exchange,提问作者Ali Prince
相关产品推荐
相关产品推荐

