I have a JSON file and need to update with new key value pair.
cuurent json:
[{'Name': 'AMAZON',
'Type': 'Web',
'eventTimeEpoch': 1611667194}]
I need to add a location parameter and update it as "USA"
.But when try to update it with below code it append to location parameter with value to end. Like below.
[{'Name': 'AMAZON',
'Type': 'Web',
'eventTimeEpoch': 1611667194,
'location': 'USA'}]
How can I add this location
parameter after the Name
.
Expected output:
[{'Name': 'AMAZON',
'location': 'USA',
'Type': 'Web',
'eventTimeEpoch': 1611667194
}]
Current code:
filename='test.json'
jsonFile = open(filename, "r") # Open the JSON file for reading
data = json.load(jsonFile)
jsonFile.close()
data[0]["location"] = "USA"
data
2
Answers
But you can do a simple hack to keep it in the same order using the dictionary as well, Like this
First off, your current JSON file is not correctly formatted. JSON needs double quotes not single quotes.
While the order of the inserted key-value pairs is guaranteed to be preserved in Python 3.7 above, you don’t have any option to "insert" to specific location inside a dictionary.(like
list
for example.) And people usually don’t count on the order of the keys when working with JSON files. You get your values by "keys" anyway.With that being said, you can do something like:
This way we created a new dictionary with the desired order. Since
"location"
key is near to the start of the items, we pop first key-value pair, then insert the"location"
key, then unpack the rest with**
operator.