3

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

2 Answers 2

4

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:

import json

with open("test.json") as f:
    data = json.load(f)
    print(data)

new_d = {"Name": data[0].pop("Name"), "location": "USA", **data[0]}
print(new_d)

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!!!Could you please clarify one thing. You pop the first key value('Name': 'AMAZON') and add the location and then unpack. If so why the location doesnt come as first key value. Since now location is the first key value after the removing "Name"
@Adam new_d is a separate dictionary from data[0]. Yes after we popped 'name', data[0]'s content is {'Type': 'Web', 'eventTimeEpoch': 1611667194}. Now in new_d, we have the popped item as the first item, "location" as the second item and the rest of the data[0] which is {'Type': 'Web', 'eventTimeEpoch': 1611667194} as the third and forth. Did I able to explain it clearly?
Perfectly explained!!! Thanks again
2

But you can do a simple hack to keep it in the same order using the dictionary as well, Like this

In [4]: d = [{'Name': 'AMAZON',
   ...:   'Type': 'Web',
   ...:   'eventTimeEpoch': 1611667194}]

In [5]: pos = list(d[0].keys()).index('Name')
   ...: items = list(d[0].items())
   ...: items.insert(pos+1, ('location', 'USA'))
   ...: d[0] = dict(items)

In [6]: print(d)
Out[6]: 
[{'Name': 'AMAZON',
  'location': 'USA',
  'Type': 'Web',
  'eventTimeEpoch': 1611667194}]

1 Comment

Python's builtin dict already preserves the order(3.7+). No need for OrderDict for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.