用JSON文件中的子模式替换空对象?

2024-09-25 18:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用子模式替换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)

Tags: nofromapijsonfalseformatdataroute
1条回答
网友
1楼 · 发布于 2024-09-25 18:23:49

您正在为字符串指定格式, 只要去掉引号就行了。你知道吗

route["format"] = {"dateFormat": "dayShortMonthYear"}

相关问题 更多 >