Genspec Genspec - 4 years ago 93
Python Question

Replace null object with Subschema in a JSON file?

I want to replace a

null
value in a JSON object with a subschema.

I want to change

"format": null


to

"format": {
"dateFormat": "dayShortMonthYear"
}


Using the code below, I get the following result for
"format":
(which I don't think is correct):

"format": "{\"dateFormat\": \"dayShortMonthYear\"}",


This is my code. Any help will be greatly apreciated.

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)

Answer Source

You are assigning format to a string, just remove the quotes and it should work.

route["format"] = {"dateFormat": "dayShortMonthYear"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download