我需要解析JSON文件,该文件与下面的示例中的相同。我需要将每个属性值与其他属性值一起添加到所有人中,例如p_30_34_yrs
和其他属性p_30_34_yrs
等等。我需要JSON文件作为结果与这些添加的值 - p_30_34_yrs
一起,p_tot在一起等等。请帮助我,因为我对Python很新。我可以通过load()
解析它并给我dict
,但当我dict["features"]
时,它会将其转换为list
甚至list
我我无法获取每个属性键值,我应用sum()
。
Example:
{
"type":"..",
"box":[..],
"crs":{
..
},
"features":[
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [..]
},
"properties": {
"p_30_34_yrs": 421,
"p_tot": 3210,
"year": "2014",
"p_75_79_yrs": 30,
"p_40_44_yrs": 259,
"p_55_59_yrs": 174,
"p_65_69_yrs": 96
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb1"
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
..
]
},
"properties": {
"p_30_34_yrs": 2316,
"p_tot": 22690,
"year": "2014",
"p_75_79_yrs": 461,
"p_40_44_yrs": 1211,
"p_55_59_yrs": 1031,
"p_65_69_yrs": 1071
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb0"
},
and same way 6 more times.
]
}
答案 0 :(得分:1)
这样的东西(测试代码)?
jsn = {
"type": "..",
"box": "[..]",
"features": [{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": "[..]"
},
"properties": {
"p_30_34_yrs": 421,
"p_tot": 3210,
"year": "2014",
"p_75_79_yrs": 30,
"p_40_44_yrs": 259,
"p_55_59_yrs": 174,
"p_65_69_yrs": 96
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb1"
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"p_30_34_yrs": 2316,
"p_tot": 22690,
"year": "2014",
"p_75_79_yrs": 461,
"p_40_44_yrs": 1211,
"p_55_59_yrs": 1031,
"p_65_69_yrs": 1071
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb0"
}
]
}
data = jsn["features"]
props = {"p_30_34_yrs": 0,
"p_tot": 0,
"p_75_79_yrs": 0,
"p_40_44_yrs": 0,
"p_55_59_yrs": 0,
"p_65_69_yrs": 0}
for feat in data:
if "properties" in feat:
if "p_30_34_yrs" in feat["properties"]: props["p_30_34_yrs"] += feat["properties"]["p_30_34_yrs"]
if "p_tot" in feat["properties"]: props["p_tot"] += feat["properties"]["p_tot"]
if "p_75_79_yrs" in feat["properties"]: props["p_75_79_yrs"] += feat["properties"]["p_75_79_yrs"]
if "p_40_44_yrs" in feat["properties"]: props["p_40_44_yrs"] += feat["properties"]["p_40_44_yrs"]
if "p_55_59_yrs" in feat["properties"]: props["p_55_59_yrs"] += feat["properties"]["p_55_59_yrs"]
if "p_65_69_yrs" in feat["properties"]: props["p_65_69_yrs"] += feat["properties"]["p_65_69_yrs"]
print(props)