0

I want to add new element to json object to specific index/position.

if I use data["country"] = "value", it is adding to the end of the json object.

import json

data = json.loads('''{"user_name": "xcv","password": "dsjvwebv","age":27,"address":{"country_name": "value",
                  "state_name":"tamil nadu",  "district" :"Tirunelveli"    },"work_history": [      {"name": "CSC", 
                  "location": "chennai"},      {"name": "Saturam", "location": "bangalore"},      {"name": "crayon", 
                  "location": "chennai"}    ],"marital_status" :"married","disability":"No"}''')
del data["password"]
country = data["address"]["country_name"]
data.pop("disability")
data.pop("address")
data["country"] = country
i=0
for j in data["work_history"]:
    if j["location"] != "chennai":
        data["work_history"].pop(i)
    i = i+1

print(data)

i want the country value to be at position as in the output below.

{'user_name': 'xcv', 'age': 27, 'country': 'value', 'work_history': [{'name': 'CSC', 'location': 'chennai'}, {'name': 'crayon', 'location': 'chennai'}], 'marital_status': 'married}
chitown88
  • 27,527
  • 4
  • 30
  • 59
meghana V
  • 19
  • 1
  • 6
  • 1
    json uses key-value-pairs. its not supposed to place elements by order – Florian H Jun 04 '19 at 09:59
  • Possible duplicate of [Inserting values into specific locations in a json file with Python](https://stackoverflow.com/questions/32824603/inserting-values-into-specific-locations-in-a-json-file-with-python) – Underoos Jun 04 '19 at 10:00
  • @SukumarRdjf This is not I am looking for. I don't have list of values. its only single key value pair. and i want it in a specified index. – meghana V Jun 04 '19 at 10:32
  • @meghanaV Can you explain why the elements position is important? – balderman Jun 04 '19 at 11:41
  • 1
    json structures do not have index positions since there is no inheritance "order" to keys within the structure. Objects in JavaScript are collections of unordered properties. You do not call values of keys by an index position, you call them by the key names themselves – chitown88 Jun 04 '19 at 11:50
  • https://stackoverflow.com/questions/18871217/how-to-custom-sort-a-list-of-dict-to-use-in-json-dumps Answers your question. It allows the json data to be output in a specified order using Ordered Dicts. – scotty3785 Jun 04 '19 at 14:01

0 Answers0