我想用子模式替换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)
答案 0 :(得分:1)
您正在为字符串分配格式, 只需删除引号就可以了。
route["format"] = {"dateFormat": "dayShortMonthYear"}