0

I am new to python, am used to php, and I am trying to figure out how to combine the json.loads from multiple data sets into one.

This is what I have:

import json
var = json.loads('{"root": [{"item 1": "1","item 2": "2","List1": [1,2,3]}]}')
var2 = json.loads('{"root": [{"item 1": "1","item 2": "2","List2": [1,2,3]}]}')
import pprint

print 'var:'
pprint.pprint(var);
print 'var2:'
pprint.pprint(var2);

print 'deepcopy:' 
import copy;
var3 = var;
var3 = copy.deepcopy(var2);
pprint.pprint(var3);

print 'dict copy:'
pprint.pprint(dict(var.items() + var2.items()));

Results in:

var: {u'root': [{u'List1': [1, 2, 3], u'item 1': u'1', u'item 2': u'2'}]}

var2: {u'root': [{u'List2': [1, 2, 3], u'item 1': u'1', u'item 2': u'2'}]}

deepcopy: {u'root': [{u'List2': [1, 2, 3], u'item 1': u'1', u'item 2': u'2'}]}

dict copy: {u'root': [{u'List2': [1, 2, 3], u'item 1': u'1', u'item 2': u'2'}]}

I am looking for a result like (including both lists), but including the duplicate items would be helpful as well, as then I will be heading in the right direction:

{u'root': [{u'List1': [1, 2, 3], u'List2': [1, 2, 3], u'item 1': u'1', u'item 2': u'2'}]}

Jon H
  • 193
  • 3
  • 15
  • check http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression – brainovergrow Nov 23 '14 at 14:15
  • Thanks, that's where I got the "dict copy" item that I tried, print result #4. Unfortunately that doesn't do it, I believe its because the parsed JSON is a mixture of dictionaries and lists. – Jon H Nov 23 '14 at 14:32
  • @brainovergrow that situation is a bit more complex than the one OP is in – dursk Nov 23 '14 at 15:06

2 Answers2

1

This should give you want you want:

var3 = var
var3['root'][0].update(var2['root'][0])

Although I'm not sure why the value at the key 'root' is a list with a single dict element.
If this isn't necessary, it'd be a lot cleaner if the value was just the dict itself, then you can do:

var3 = var
var3['root'].update(var2['root'])
dursk
  • 4,435
  • 2
  • 19
  • 30
  • I'm loading in multiple JSON files and I need to combine them into one array. That structure is a simplified example of how the JSON files load. This works thanks, so if I wanted to make this work for all cases, I could just create a function to loop through every element of array 1 and update with array 2? – Jon H Nov 23 '14 at 16:46
0

This is not a JSON question, but a Python dict() one, since the output of json.loads() is a dictionary. What you really want is a way to combine 2 dictionaries. To create the desired result, you can do this

var3['root'] = var1.update(var2['root'])

Cheers!

oxymor0n
  • 1,089
  • 7
  • 15