我是真正的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。这行得通。关键是,我需要使用迭代器来更改日期字段以添加日期,但是我仍然坚持更改此字段。
有什么建议吗?
谢谢!
由于您的问题有点含糊,我只能猜测您是在尝试直接修改数据的JSON版本,而在将Python对象转换为JSON之前应先对其进行修改,如下所示:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句