Home > Net >  How can I change multiple keys in a JSON file that has multiple dictionaries which incorporate the s
How can I change multiple keys in a JSON file that has multiple dictionaries which incorporate the s

Time:12-30

I currently am attempting to edit a JSON file that has multiple listed dictionaries that incorporate the same keys but different values. I would like to change specific keys (the same ones) in every dictionary within the file. How can I do this?

For Example:

"JSON_FILE" [

    {"type" : "person", 'attributes" : { "Name" : "Jack, "Age" : 24, "Hight" : 6.2}}

    {"type" : "person", "attributes" : { "Name" : "Brent", "Age" : 15, "Hight" : 5.6}}

    {"type" : "person", "attributes" : { "Name" : "Matt", "Age" : 30, "Hight" : 4.9}}  ] 

I would like to change all the 'Name' keys to be labeled as " 'NAME' " and all the 'Hight' keys to be labeled as 'HIGHT'.

I am using Python and this is a data set of 100 dictionaries I am attempting to edit so going through one at a time is not efficient.

CodePudding user response:

I'm assuming the schema is actually well-formed ("attributes" in quotes, use of double rather than single quotes, commas between objects in a list).

You can do the following to rename your fields:

import json

data = json.load(open('your_file_name.json', 'r'))
for data_entry in data:
    # Add new 'NAME' field, then delete old 'Name' field.
    data_entry['attributes']['NAME'] = data_entry['attributes']['Name']
    del data_entry['attributes']['Name']

    # Add new 'HIGHT' (sic) field, then delete old 'Hight' field.
    data_entry['attributes']['HIGHT'] = data_entry['attributes']['Hight']
    del data_entry['attributes']['Hight']

with open('your_file_name.json', 'w') as output_file:
    output_file.write(json.dumps(data))

CodePudding user response:

If you have multiple keys under attributes to upper case, you can do the following:

import json

file_path = "path/to/file"
fields_to_upper = ["Name", "Hight", "Age"]
with open(file_path, "r") as f:
    data = json.load(f)
    for row in data:
        for field in fields_to_upper:
            row["attributes"][field.upper()] = row["attributes"].pop(field)
with open(file_path, "w") as f:
    f.write(json.dumps(data))

If you want to upper case all the keys under attributes, try:

with open(file_path, "r") as f:
    data = json.load(f)
    for row in data:
        for key in row["attributes"].keys():
            row["attributes"][key.upper()] = row["attributes"].pop(key)
with open(file_path, "w") as f:
    f.write(json.dumps(data))
  • Related