skip to Main Content

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


  1. You need to convert data back to string and insert it back to the original dictionary

    with open(os.path.join(root, file_name)) as jsonFile:
        d = json.load(jsonFile)
        for k in d:
            data = json.loads(d[k])
            data['sampleID'] = 'newValue'
            d[k] = json.dumps(data)
    
    with open(os.path.join(root, file_name), 'w') as jsonFile:
        json.dump(d, jsonFile, indent=4)
    

    Output

    {"key": "{"url": "DEFAULT", "id": "tzz22s6a", "sampleID": "newValue", "isPassRequired": false, "isKeyRequired": true, "materialType": "SATIN", "clothType": "DEFAULT"}"}
    

    If you don’t really need the json in this format, replacing d[k] = json.dumps(data) with d[k] = data will also give you a valid json.

    Login or Signup to reply.
  2. 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 reassign key to the updated data JSON obj such as:

    with open(os.path.join(root, file_name)) as jsonFile:
        d = json.load(jsonFile)
        for key in d:
            # You shouldn't need to load this again on the line below if the input json is valid but in your example it is not.
            data = json.loads(d[key])
            data['sampleID'] = 'newValue'
            # Set "key" in d to be the updated data dict.
            d[key] = data
    

    Additional points:

    • The iterator of d will loop through the keys so I changed it to for key in d to make it clearer.
    • Your nested JSON in the pasted example isn’t value due to the backslash characters so to reproduce your code I did this:
    import json
    import re
    
    data = {"key":"{"url":"DEFAULT","id":"tzz22s6a","sampleID":"jahsdioadhao","isPassRequired":false,"isKeyRequired":true,"materialType":"SATIN","clothType":"DEFAULT"}"}
    
    # Create a regex compiler
    pattern = re.compile(r"\")
    
    # Sub the characters in pattern with empty string `""` in place on data["key"]
    pattern.sub("", data["key"])
    
    # Set data["key"] in place to be the dict of the json string.
    data["key"] = json.loads(data["key"])
    
    # Replace the value of "sampleID" in "key"
    data["key"]["sampleID"] = "newValue"
    
    # which produces
    {'key': {'url': 'DEFAULT',
      'id': 'tzz22s6a',
      'sampleID': 'newValue',
      'isPassRequired': False,
      'isKeyRequired': True,
      'materialType': 'SATIN',
      'clothType': 'DEFAULT'}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search