【问题标题】:Combine two geojson state zipcode files?结合两个geojson状态邮政编码文件?
【发布时间】:2021-02-17 10:05:37
【问题描述】:

我正在做一个需要使用US States Zip Code Data 的项目。我想合并两个 geojson 文件,同时保留这些文件中的数据。 geojson-merge https://github.com/mapbox/geojson-merge 这样做,但我希望有一个基于 python 的解决方案。

每个州都有一个单独的 *.json 文件。例如:

  1. mt_montana_zip_codes_geo.min.json

  2. nd_north_dakota_zip_codes_geo.min.json

    import json
    
    nd_boundary_file = r"C:\Data_ZipCodes_States\State-zip-code-GeoJSON-master" \
              r"\nd_north_dakota_zip_codes_geo.min.json"
    
    with open(nd_boundary_file, 'r') as f:
        nd_zipcode_boundary = json.load(f)
    
    mt_boundary_file = r"C:\\Data_ZipCodes_States\State-zip-code-GeoJSON-master" \
              r"\mt_montana_zip_codes_geo.min.json"
    
    with open(mt_boundary_file, 'r') as f:
        mt_zipcode_boundary = json.load(f)
    
    
    #This overwrote the mt_zipcode_boundary with the nd_zipcode_boundary into merged
    #merged = {**mt_zipcode_boundary, **nd_zipcode_boundary}
    
    #produced a file with two json objects one 'mt' and the other 'nd'
    data = {'mt': mt_zipcode_boundary, 'nd':nd_zipcode_boundary}
    
    #Also overwrote mt_zipcode_boundary
    mt_zipcode_boundary.update(nd_zipcode_boundary)
    

如何编写代码将这两个 geojson 文件合并到一个文件中?

【问题讨论】:

  • 它们的结构是否相同?与列中一样。
  • @martinfleis 是的,它们具有相同的结构。

标签: python json geojson geopandas


【解决方案1】:

这样的事情呢?

import json

fc = {
    'type': 'FeatureCollection',
    'features': []
}

with open("mt_montana_zip_codes_geo.min.json") as json_file:
    obj = json.load(json_file)
    fc['features'].extend(obj['features'])

with open("nd_north_dakota_zip_codes_geo.min.json") as json_file:
    obj = json.load(json_file)
    fc['features'].extend(obj['features'])

with open("merged.json", "w") as outfile:
    json.dump(fc, outfile)
    

【讨论】:

  • 就像一个魅力。我不明白,但我非常感谢你向我展示工作代码。我需要解决这个问题...
  • fc 是一个字典,其中 'features' 是一个键,它的值是一个列表。 json.load 从文件中读取数据,解析数据并返回包含数据的字典。 list.extend(list_to_add) 将 list_to_add 元素添加到列表的末尾。 json.dump(fc, outfile) 将 fc 字典写入 outfile 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 2018-03-14
相关资源
最近更新 更多