hellowrld hellowrld - 1 year ago 91
JSON Question

Combining multiple jsons into one json python

I have three jsons:

a = {'name':'Tyler', 'd1': [[1,1],[2,2],[3,3]], 'd2': [[2,2],[4,4],[6,6]]}
b = {'name':'Matt', 'd1': [[3,3],[4,4],[5,5]], 'd2': [[6,6],[8,8],[10,10]]}
c = {'name':'Sarah', 'd1': [[2,1],[4,2],[6,3]], 'd2': [[4,2],[8,4],[12,6]]}


I am trying to combine a,b,c into one json such that they have the following format

d = [{'name':'Tyler', 'd1': [[1,1],[2,2],[3,3]], 'd2': [[2,2],[4,4],[6,6]]},{'name':'Matt', 'd1': [[3,3],[4,4],[5,5]], 'd2': [[6,6],[8,8],[10,10]]},{'name':'Sarah', 'd1': [[2,1],[4,2],[6,3]], 'd2': [[4,2],[8,4],[12,6]]}]


This json d is going to be passed into flask so that I can use it in a d3 chart.

I have tried creating a list d = [a,b,c] and then letting e = json.dumps(d) but this does not work. I have also tried to create an empty dictionary and add the a,b,c in and then dump this to json but this does not work. Are there any nice implementations for this? Thanks

Answer Source

Just use json.dumps with a list:

import json

a = {'name':'Tyler', 'd1': [[1,1],[2,2],[3,3]], 'd2': [[2,2],[4,4],[6,6]]}
b = {'name':'Matt', 'd1': [[3,3],[4,4],[5,5]], 'd2': [[6,6],[8,8],[10,10]]}
c = {'name':'Sarah', 'd1': [[2,1],[4,2],[6,3]], 'd2': [[4,2],[8,4],[12,6]]}

print(json.dumps([a, b, c]))

Output, formatted for easier reading:

[{"d2": [[2, 2], [4, 4], [6, 6]], "d1": [[1, 1], [2, 2], [3, 3]], "name": "Tyler"}, 
 {"d2": [[6, 6], [8, 8], [10, 10]], "d1": [[3, 3], [4, 4], [5, 5]], "name": "Matt"}, 
 {"d2": [[4, 2], [8, 4], [12, 6]], "d1": [[2, 1], [4, 2], [6, 3]], "name": "Sarah"}]