2

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
S.B
  • 13,077
  • 10
  • 22
  • 49
Adam
  • 129
  • 6
  • In JSON, or Python dictionnary, there is no such concept of "position" for a key. EDIT: wait, I may be wrong here for Python: https://stackoverflow.com/a/39537308/6213883 – Itération 122442 Dec 30 '22 at 07:43
  • Does this answer your question? [How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared) – Cow Dec 30 '22 at 07:46

2 Answers2

3

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.

S.B
  • 13,077
  • 10
  • 22
  • 49
  • 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 Dec 30 '22 at 08:57
  • 1
    @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? – S.B Dec 30 '22 at 09:01
  • 1
    Perfectly explained!!! Thanks again – Adam Dec 30 '22 at 09:05
1

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
    Python's builtin `dict` already preserves the order(3.7+). No need for `OrderDict` for that. – S.B Dec 30 '22 at 07:54