如何解决 fetch 返回的 JSON 数据被意外转为字符串的问题

本文详解在使用 javascript fetch 调用 django geojson api 时,因误用 `json.stringify()` 导致响应对象被二次序列化为字符串、进而无法访问 `.features` 等属性的典型错误及修复方法。

在前端通过 fetch() 请求 Django 后端返回的 GeoJSON 数据时,一个常见却容易被忽视的错误是:在已将 HTTP 响应体解析为 JavaScript 对象后,又调用了 JSON.stringify(),导致数据退化为原始字符串。这正是你遇到 typeof data === 'string' 且 data.features 为 undefined 的根本原因。

来看原始代码的问题链:

fetch('/guidebook/api/peak-data/')
  .then(response => response.json())        // ✅ 正确:将响应体解析为 JS 对象(如 { type: "FeatureCollection", features: [...] })
  .then(response => JSON.stringify(response)) // ❌ 错误:又把它变回字符串!此时 response 已是对象,无需再 stringify
  .then(data => {
    console.log('Type of data:', typeof data);        // → "string"
    console.log('Type of features:', typeof data.features); // → undefined(字符串没有 .features 属性)
  });

response.json() 返回的是一个 Promise,其 resolved 值是已解析的 JavaScript 对象(例如 GeoJSON 格式的 { "type": "FeatureCollection", "features": [...] })。而 JSON.stringify() 的作用是将该对象序列化为 JSON 字符串——这不仅多余,更会破坏后续的数据结构访问能力。

✅ 正确做法是:移除多余的 JSON.stringify() 步骤,直接在解析后的对象上操作

fetch('/guidebook/api/peak-data/')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status = ${response.status}`);
    }
    return response.json(); // 返回解析后的 GeoJSON 对象
  })
  .then(geojsonData => {
    console.log('Parsed GeoJSON object:', geojsonData);
    console.log('Type of data:', typeof geojsonData); // → "object"
    console.log('Features count:', geojsonData.features?.length || 0);

    // ✅ 现在可以安全访问 features、coordinates 等属性
    if (Array.isArray(geojsonData.features)) {
      geojsonData.features.forEach(feature => {
        const coords = feature.geometry?.coordinates;
        const name = feature.properties?.peak_name;
        console.log(`Peak: ${name}, Coordinates:`, coords);
      });
    }
  })
  .catch(error => {
    console.error('Fetch or parsing failed:', error);
  });

⚠️ 补充注意事项:

  • Django 后端使用 serialize('geojson', ...) 生成的是标准 GeoJSON 字符串,配合 JsonResponse(..., safe=False) 可正确返回(注意:safe=False 是必需的,因为 serialize() 返回的是字符串而非字典);

  • 更推荐的后端写法(提升类型安全性)是先解析再构造 JsonResponse:

    from django.http import JsonResponse
    from django.core.serializers.json import DjangoJSONEncoder
    import json
    
    def get_peak_data(request):
        peaks = Peak.objects.all()
        geojson_str = serialize('geojson', peaks, geometry_field='peak_coordinates')
        geojson_obj = json.loads(geojson_str)  # 转为 Python dict
        return JsonResponse(geojson_obj, encoder=DjangoJSONEncoder)

    这样可避免 safe=False 的潜在风险,也更符合 JsonResponse 的设计意图。

总结:response.json() 是“解析”,JSON.stringify() 是“序列化”——二者方向相反,切勿在已解析的对象上重复序列化。保持数据为原生对象形态,才能顺利访问 .features、.geometry.coordinates 等嵌套属性,真正发挥 GeoJSON 的结构化优势。