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

如何用Python解析JSON并筛选含TR35-districts的要素?

解析FeatureCollection提取指定Feature的实现方法

以下提供两种常用编程语言的实现方案,直接针对需求处理JSON数据:

JavaScript(Node.js环境)

const fs = require('fs');

// 读取目标JSON文件
const featureCollection = JSON.parse(fs.readFileSync('your-file.json', 'utf8'));

// 过滤出符合条件的Feature并保留指定字段
const filteredFeatures = featureCollection.features
  .filter(feature => feature.properties?.network === 'TR35-districts')
  .map(feature => ({
    type: feature.type,
    properties: feature.properties,
    geometry: feature.geometry
  }));

// 可选择将结果写入新文件
// fs.writeFileSync('filtered-result.json', JSON.stringify(filteredFeatures, null, 2));
console.log(filteredFeatures);

Python

import json

# 读取JSON文件
with open('your-file.json', 'r', encoding='utf-8') as file:
    feature_collection = json.load(file)

filtered_features = []
for feature in feature_collection['features']:
    # 避免字段不存在引发报错
    if feature.get('properties', {}).get('network') == 'TR35-districts':
        # 保留指定字段
        filtered_feature = {
            'type': feature['type'],
            'properties': feature['properties'],
            'geometry': feature['geometry']
        }
        filtered_features.append(filtered_feature)

# 输出结果或写入文件
print(filtered_features)
# with open('filtered-result.json', 'w', encoding='utf-8') as file:
#     json.dump(filtered_features, file, indent=2)

注意事项

  • 替换代码中的your-file.json为你的实际文件路径
  • 代码加入了容错处理,避免因部分Feature缺少properties或network字段导致程序崩溃
  • 最终得到的数组就是符合要求的Feature对象集合

内容的提问来源于stack exchange,提问作者Altan Halıgür

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:54:55