You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取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-except blocks to handle cases where the response structure might be missing fields (e.g., if the API returns an error), to avoid unexpected KeyError crashes.
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:49:15