I have a json file consisting of a dict of String:String
I tried to first load the file using json.load and then update the dict but when I dump the updated dict I lose the key. Unable to figure out how to update a value.
I’m trying to update the value of sampleID to something else and write back to the same file.
{"key":"{"url":"DEFAULT","id":"tzz22s6a","sampleID":"jahsdioadhao","isPassRequired":false,"isKeyRequired":true,"materialType":"SATIN","clothType":"DEFAULT"}"}
what I tried so far, which updates the value of sampleId but the format of the file is changed and also I loose the key i.e., "key"
with open(os.path.join(root, file_name)) as jsonFile:
d = json.load(jsonFile)
for values in d:
data = json.loads(d[values])
data['sampleID'] = 'newValue'
with open(os.path.join(root, file_name), 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
2
Answers
You need to convert
data
back to string and insert it back to the original dictionaryOutput
If you don’t really need the
json
in this format, replacingd[k] = json.dumps(data)
withd[k] = data
will also give you a validjson
.It looks like your nested json object isn’t getting serialised properly from the sample JSON you provided.
To update the nested key you should modify it either in place inside the
d
object, or reassignkey
to the updateddata
JSON obj such as:Additional points:
d
will loop through the keys so I changed it tofor key in d
to make it clearer.