Home > Net >  add new value to specific position in JSON using python
add new value to specific position in JSON using python

Time:12-30

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

CodePudding user response:

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.

CodePudding user response:

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}]
  • Related