Python JSON生成新的嵌套元素

时间:2014-07-14 10:21:23

标签: python json

我有一个像这样的JSON:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "timestamp": 1400162618,
        "style": "",
        "category": "sdf",
        "popup": "sd"
      }
    }
  ]
}

现在我想添加"样式"几个带有值的新子元素。新的JSON应如下所示:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "timestamp": 1400162618,
        "style": {
             "radius": 8,
             "color": "#428ed2"
      },
        "category": "sdf",
        "popup": "sd"
      }
    }
  ]
}

我想用

来做到这一点
import json

geoJson = json.load(open('sample.geojson'))

features = geoJson["features"]
for feat in features:
  feat["properties"]["style"]["radius"] = 2

但我明白了:KeyError:' style'

如何为JSON分配新元素?

1 个答案:

答案 0 :(得分:0)

您需要先将其初始化为dict

for feat in features:
  feat["properties"]["style"] = {}  #initializing to dict
  feat["properties"]["style"]["radius"] = 2
  feat["properties"]["style"]["color"] = "#428ed2"

或直接指定字典

for feat in features:
  feat["properties"]["style"] = {"radius": 2, "color": "#428ed2"}