在Python中构建动态JSON / LIST obj

时间:2015-05-23 12:12:49

标签: python json

我是一个真正的Python新手,我在创建JSON / LIST obj时遇到了问题。 我想要最终得到的是以下JSON来发送API

{
  "request": {
    "slice": [
      {
        "origin": "AMS",
        "destination": "SYD",
        "date": "2015-06-23"
      }
    ],
    "passengers": {
      "adultCount": 1,
      "infantInLapCount": 0,
      "infantInSeatCount": 0,
      "childCount": 0,
      "seniorCount": 0
    },
    "solutions": 20,
    "refundable": false
  }
}

我想制作一个列表,然后使用dumps()函数转换为JSON。这有效。问题是,我需要用迭代器更改日期字段以添加一天,但我不得不改变这个字段。

有什么建议吗?

THX!

1 个答案:

答案 0 :(得分:3)

由于您的问题有点模糊,我只能猜测您是否正在尝试直接修改数据的JSON版本,而您应该在将其转换为JSON之前修改Python对象 ......这样的事情:

d = {
  "request": {
    "slice": [
      {
        "origin": "AMS",
        "destination": "SYD",
        "date": "2015-06-23"
      }
    ],
    "passengers": {
      "adultCount": 1,
      "infantInLapCount": 0,
      "infantInSeatCount": 0,
      "childCount": 0,
      "seniorCount": 0
    },
    "solutions": 20,
    "refundable": False  # note how this is python False, not js false!
  }
}

# then you can do:
d["request"]["slice"][0]["date"] = "2015-05-23"

# and finally convert to json:
j = json.dumps(d)

如果您将JSON作为字符串发生,则应首先将其转换为python对象,以便您可以使用它:

# if j is your json string, convert it into a python object
d = json.loads(j)

# then do your modifications as above:
d["request"]["slice"][0]["date"] = "2015-05-23"

# and finally convert back to json:
j = json.dumps(d)