我需要使用Python访问JSON文件中的数据并提取文件的特定部分

时间:2019-06-24 05:47:54

标签: python json

这是我的JSON文件。它基本上掌握着美国某些县的纬度和经度。我只需要提取STATE ID为48的那些项(对于得克萨斯州)。我尝试了一个代码,但是只序列化了文件

{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "GEO_ID": "0500000US01001", "STATE": "01", "COUNTY": "001", "NAME": "Autauga", "LSAD": "County", "CENSUSAREA": 594.436000 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -86.496774, 32.344437 ], [ -86.717897, 32.402814 ], [ -86.814912, 32.340803 ], [ -86.890581, 32.502974 ], [ -86.917595, 32.664169 ], [ -86.713390, 32.661732 ], [ -86.714219, 32.705694 ], [ -86.413116, 32.707386 ], [ -86.411172, 32.409937 ], [ -86.496774, 32.344437 ] ] ] } }
,
{ "type": "Feature", "properties": { "GEO_ID": "0500000US01009", "STATE": "01", "COUNTY": "009", "NAME": "Blount", "LSAD": "County", "CENSUSAREA": 644.776000 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -86.577799, 33.765316 ], [ -86.759144, 33.840617 ], [ -86.953664, 33.815297 ], [ -86.954305, 33.844862 ], [ -86.962960, 33.844865 ], [ -86.963358, 33.858221 ], [ -86.924387, 33.909222 ], [ -86.793914, 33.952059 ], [ -86.685365, 34.059140 ], [ -86.692061, 34.092654 ], [ -86.599632, 34.119914 ], [ -86.514881, 34.254370 ], [ -86.453020, 34.259317 ], [ -86.303516, 34.099073 ], [ -86.332723, 33.986109 ], [ -86.370152, 33.939770 ], [ -86.325622, 33.940147 ], [ -86.377532, 33.861706 ], [ -86.577528, 33.801977 ], [ -86.577799, 33.765316 ] ] ] } }
,
{ "type": "Feature", "properties": { "GEO_ID": "0500000US01017", "STATE": "01", "COUNTY": "017", "NAME": "Chambers", "LSAD": "County", "CENSUSAREA": 596.531000 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -85.184131, 32.870525 ], [ -85.123421, 32.772248 ], [ -85.132040, 32.764211 ], [ -85.136776, 32.746512 ], [ -85.285043, 32.730731 ], [ -85.593151, 32.728530 ], [ -85.593177, 33.107340 ], [ -85.232378, 33.108077 ], [ -85.223261, 33.062580 ], [ -85.221868, 33.055538 ], [ -85.184131, 32.870525 ] ] ] } }
import json

obj  = json.load(open("test.json"))
result = []


for i in range(len(obj)):
    result.append(i)

open("updated-file5.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

1 个答案:

答案 0 :(得分:0)

这应该可以帮助您。您将获得所有状态为“ 48”的项目。

import json

data = json.load(open('data.json', 'r'))

res = []

for feature in data['features']:
        if feature['properties']['STATE'] == '48':
                res.append(feature)

print(res)