如何正确处理 Django GeoJSON API 返回的 JSON 数据

本文详解在前端使用 `fetch` 调用 django 返回的 geojson 接口时,因误用 `json.stringify()` 导致数据变为字符串、丢失结构化属性(如 `.features`)的典型错误,并提供完整、安全的前后端联调方案。

你在前端代码中执行了以下链式调用:

fetch('/guidebook/api/peak-data/')
  .then(response => response.json())        // ✅ 将 HTTP 响应体解析为 JS 对象(如 GeoJSON)
  .then(response => JSON.stringify(response)) // ❌ 再次转成字符串 —— 这是问题根源!
  .then(data => {
    console.log('Type of data:', typeof data);         // → "string"
    console.log('Type of features:', typeof data.features); // → undefined(字符串无 .features 属性)
  });

response.json() 已将响应体(原始 JSON 字符串)成功解析为 JavaScript 对象(例如一个包含 type, features, crs 等字段的标准 GeoJSON 对象)。而紧接着的 JSON.stringify(response) 又将其反向序列化为字符串,导致后续所有 .features、.features[0].geometry.coordinates 等访问全部失效。

✅ 正确做法是:仅解析一次,后续直接操作 JS 对象。修正后的前端代码如下:

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);

    // ✅ 安全提取坐标示例(假设每个 feature 是 Point 类型)
    const coordinates = geojsonData.features
      ?.filter(f => f.geometry?.type === 'Point')
      .map(f => f.geometry.coordinates);
    console.log('All peak coordinates:', coordinates);

    // 后续可传给 Leaflet / Mapbox 等地图库渲染
  })
  .catch(error => {
    console.error('Failed to fetch or parse peak data:', error);
  });

⚠️ 同时,后端 Django 也需确保返回格式合规:

  • serialize('geojson', ...) 默认返回的是 字符串格式的 GeoJSON(非 Python dict),因此 JsonResponse(..., safe=False) 是必要且正确的;
  • 但务必确认 content_type='application/json' 已显式设置(你已做到),并避免额外包装或双层序列化。

? 补充建议:

  • 在 Django 视图中可加日志验证输出内容:
    def get_peak_data(request):
        peaks = Peak.objects.all()
        peak_data = serialize('geojson', peaks, geometry_field='peak_coordinates')
        # 可选:调试时打印类型与前100字符
        print("Serialized type:", type(peak_data), "Preview:", peak_data[:100])
        return JsonResponse(peak_data, safe=False, content_type='application/json')
  • 前端开发中,推荐使用 console.dir(geojsonData) 替代 console.log() 查看对象层级结构;
  • 若需进一步校验 GeoJSON 合法性,可在前端引入 geojson-validation 库。

总结:response.json() 是解析入口,JSON.stringify() 是导出出口——二者不可在同一数据流中连续使用。保持数据为原生对象形态,才能可靠访问 .features、.properties、.geometry 等 GeoJSON 标准字段,实现地理数据的精准提取与可视化。