Combine multiple json merging duplicates and adding values for a specific key in python
<p>I've looked around for a method to do this, but I can only find bits and pieces and keep getting stuck.
I want to add two sets of json, retaining all properties but adding the <code>total</code> value if a duplicate <code>owner</code> value exists.</p>

<pre><code>json1 = [{"total":101,"owner":"User1","type":8,"team":"Team1"},
{"total":44,"owner":"User2","type":8,"team":"Team1"},
{"total":22,"owner":"User3","type":8,"team":"Team2"}]

json2 = [{"total":12,"owner":"User1","type":8,"team":"Team1"},
{"total":33,"owner":"User3","type":8,"team":"Team2"},
{"total":18,"owner":"User4","type":8,"team":"Team1"}]
</code></pre>

<p>I want to have the output look like this</p>

<pre><code>finaljson = [{"total":113,"owner":"User1","type":8,"team":"Team1"},
{"total":44,"owner":"User2","type":8,"team":"Team1"},
{"total":55,"owner":"User3","type":8,"team":"Team2"},
{"total":18,"owner":"User4","type":8,"team":"Team1"}]
</code></pre>

<p>Alternatively, how would I reach my final <code>finaljson</code> if I had a single json set and wanted to find duplicate <code>owner</code> and merge <code>total</code> the same as above.</p>

<p><code>mergedjson = json1.extend(json2)</code> becomes <code>finaljson</code></p>

<p>Thanks!</p>

<p>Try this, although this wont be the best solution.</p>

<pre><code>def merge_json(json1, json2):
    data = {}
    for val in json1+json2:
        key = val["owner"]
        if key in data:
            data[key]['total'] = data[key]['total']+val['total']
        else:
            data[key] = val
    return list(data.values())
</code></pre>

<p><strong><a href="https://repl.it/DoKf" rel="nofollow">DEMO</a></strong></p>

python json merge