Only write to specific parts of a JSON object using Python

I can't seem to figure out how I can write only to specific parts of a JSON object.

The below displays the object (there would be many more users in reality)

{"User 0": {"friends": ["tom", "harry", "will"], "preference": 5, "team": "x", "blocked": [20210708, 20210726, 20210729, 20210719, 20210715, 20210727, 20210712, 20210812, 20210729], "required": [20210825, 20210809, 20210820, 20210730, 20210707, 20210827, 20210720, 20210722, 20210818], "absent": [20210802, 20210813, 20210823]}},
{"User 1": {"friends": ["chris", "steve", "will", "john"], "preference": 3, "team": "z", "blocked": [20210715, 20210712, 20210720, 20210830, 20210701, 20210805, 20210720, 20210804, 20210728], "required": [20210706, 20210727, 20210701, 20210713, 20210705, 20210715, 20210707, 20210729, 20210817], "absent": [20210816, 20210722, 20210720]}}

and for each user, I only want to change the "required", "blocked", "absent" and "preference" to the values of the specified variables (for each person, the "required"...."absent" are all different. Is there a way to do this?

for person in range(totalUsers):
    required = assignDays(O)
    blocked = assignDays(R)
    absent = assignDays(A)
    preference = preferenceOnDays()
    with open('TestScript.json', 'a') as outfile:
        data = {"user": {
            "names": [],
            "preference": preference,
            "team": "x",
            "blocked": blocked,
            "required": required,
            "absent": absent}}
        json.dump(data, outfile)
        outfile.write('\n')

1 answer

  • answered 2021-04-21 13:55 Paul Becotte

    JSON is a textual representation of a data structure. To get what you want, all you have to do is load the data from the text file into a data structure, modify the data structure, and then write the newly modified structure back to a text file.

    # Read the data from the text file into a python dictionary
    data = json.load(outfile)
    
    # Create a new dictionary, starting with the original one and overriding
    # whatever values you want to change. You could also do a series of
    # data["required"] = "new value"
    # lines instead (if you prefer)
    updated_data = dict(data, requied=required, blocked=blocked, ...)
    
    # now that we have a new dictionary with the data that we want in it,
    # write it to a text file
    json.dump(data, outfile)