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

Python实现:向GeoJSON添加var data=并保存为.js文件时出现None值问题

问题原因及解决方法

问题根源

你用了json.dump()函数,这个函数会直接把Python对象序列化后写入文件,它的返回值是None。你把geojson_str赋值给这个返回值,自然得到的就是None,所以写入js文件时会出现var data = None;。

解决代码

换成json.dumps()(注意末尾的s)就行,它会把Python对象转换成GeoJSON格式的字符串,返回这个字符串供你后续处理。修改后的代码如下:

import json
# 假设你已正确导入FeatureCollection并生成features
collection = FeatureCollection(features)

# 将GeoJSON数据转换为字符串
geojson_str = json.dumps(collection, indent=4)

# 写入geoData.geojson文件
with open("geoData.geojson", "w") as f:
    f.write(geojson_str)

# 写入geometry.js文件
output_filename = 'geometry.js'
with open(output_filename, 'w') as output_file:
    output_file.write(f'var data = {geojson_str};')

关键区别说明

  • json.dump(obj, file):直接把序列化内容写入文件,无返回值(返回None)
  • json.dumps(obj):把Python对象序列化为字符串,返回该字符串,适合需要二次处理内容的场景

内容的提问来源于stack exchange,提问作者Bruno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:36:18