我想用子架构替换 JSON 对象中的null
值。
我想改变
"format": null
自
"format": {
"dateFormat": "dayShortMonthYear"
}
使用下面的代码,我得到了以下"format":
结果(我认为这是不正确的(:
"format": "{"dateFormat": "dayShortMonthYear"}",
这是我的代码。任何帮助将不胜感激。
import json
data_from_api = """{
"response_code": 200,
"train_number": "12229",
"position": "at Source",
"route": [
{
"no": 1,
"has_arrived": false,
"has_departed": false,
"schdep": "22:15",
"actarr": "00:00",
"distance": "0",
"day": 0,
"format": null
},
{
"actdep": "23:40",
"scharr": "23:38",
"schdep": "23:40",
"actarr": "23:38",
"no": 2,
"has_departed": false,
"scharr_date": "15 Nov 2015",
"has_arrived": false,
"station": "HRI",
"distance": "101",
"actarr_date": "15 Nov 2015",
"day": 0,
"format": {
"dateFormat": "dayShortMonthYear"
}
}
]
}"""
info = json.loads(data_from_api)
for route in info["route"]:
if route["format"] is None:
print json.dumps(route, indent=4, sort_keys=True)
route["format"] = '{"dateFormat": "dayShortMonthYear"}'
print json.dumps(route, indent=4, sort_keys=True)
您正在为字符串分配格式,只需删除引号,它应该可以工作。
route["format"] = {"dateFormat": "dayShortMonthYear"}