Thra
Thra

Reputation: 87

How to append the list of dictionary to same list in python?

I'm having a JSON with nested values. I need to remove the key of the nested field and need to keep the values as plain JSON.

JSON(Structure of my JSON)

[
  {
"id":"101",
"name":"User1",
"place":{ 
    "city":"City1",
    "district":"District1",
    "state":"State1",
    "country":"Country1" 
    },
"access":[{"status":"available"}]
  }
]

I need to get the JSON output as:

Expected Output:

[
 {
 "id":"101",
 "name":"User1",
 "city":"City1",
 "district":"District1",
 "state":"State1",
 "country":"Country1" 
 "access":[{"status":"available"}]
 }
]

What i need is:

  1. I need to parse the JSON
  2. Get the Placefield out of the JSON
  3. Remove the key and brackets and append the values to existing

Python

for i in range(0,len(json_data)):
   place_data = json_data[i]['place']
   print(type(place_data)) #dict
   del place_data['place'] 

Any approach to get the expected output in python.?

Upvotes: 1

Views: 68

Answers (2)

collinsuz
collinsuz

Reputation: 459

Another way to accomplish this with multiple "keys" updated... This would only work for a single nested level as described in the original question

def expand(array):
    flatten = list()
    for obj in array:
        temp = {}
        for key, value in obj.items():
            if isinstance(value, dict):
                temp.update(value)
            else:
                temp.update({key:value})
        flatten.append(temp)    
    return flatten  

Upvotes: 0

Teejay Bruno
Teejay Bruno

Reputation: 2159

One way to accomplish this could be by

for i in json_data:
    i.update(i.pop("place"))

Upvotes: 2

Related Questions