0

I am trying to merge a list of dictionaries into a single json object to be consumed by another json parser.

Here is my list which I fetched from a requests.get:

list = [{"name":"New York USA"}, {"id":446}]

Desired Output:

{
  "org": {
    "name": "New York USA",
    "id": 446
  }
}
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 3
    the `json` package has a `dumps` method – Nullman Jun 22 '20 at 11:17
  • 2
    The format of expected json is invalided. – jizhihaoSAMA Jun 22 '20 at 11:18
  • @jizhihaoSAMA please use normal quotes, when you edit his post. Original Post has normal Quotes – demonking Jun 22 '20 at 11:21
  • 1
    Does this answer your question? [Python: converting a list of dictionaries to json](https://stackoverflow.com/questions/21525328/python-converting-a-list-of-dictionaries-to-json) – Itamar Mushkin Jun 22 '20 at 11:28
  • Hi, and welcome to Stack Overflow. In the future, please search Stack Overflow for similar questions. – Itamar Mushkin Jun 22 '20 at 11:29
  • 1
    The title "Converting a list of dictionaries to json" doesn't currently describe the specifics described in the body, which is more of a problem of building a single object from a list of dictionaries and then converting that to JSON. – Paul Jun 22 '20 at 11:29
  • @Paul oh, can you edit / suggest an edit to the title then? And maybe find another dupe... – Itamar Mushkin Jun 22 '20 at 12:05
  • @demonking If you see the timeline of the post,you will find he didn't use the normal quote,I just added some backquotes. – jizhihaoSAMA Jun 22 '20 at 12:18

3 Answers3

1

Another solution would be Using dictionary comprehension (Note: This solution will work even if dict has multiple keys and values)

list = [{"name":"New York USA"}, {"id":446}]
data = {}
data['org'] = {key:value for item in list for key, value in item.items()}
print(data)

output: {'org': {'name': 'New York USA', 'id': 446}}

Shivam Seth
  • 677
  • 1
  • 8
  • 21
0

You can use the builtin json library

import json

list_of_dicts = [{},{}]

json_rep = json.dumps(list_of_dicts)
James Burgess
  • 487
  • 1
  • 4
  • 12
0

First merge your all dictionaries in list then, make a new dictionary thn dumps it with json.please try this below

import json
list = [{"name":"New York USA"}, {"id":446}]
def Merge(dict1, dict2): 
   res = {**dict1, **dict2} 
   return res 
dic=Merge(list[0],list[1])
print(dic)
new_json={'org':dic}
json_rep = json.dumps(new_json)
print(json_rep)

output

'{"org": {"name": "New York USA", "id": 446}}'
NAGA RAJ S
  • 452
  • 4
  • 12