Adding values to JSON in Python2.7
<p>I have been tasked with combining data from two different sources into one JSON to be used by a web service. I decided to go with flask which I have found to be so easy to use.
Anyway, I am retrieving JSON that looks like this ( via urlib2 )....</p>

<pre><code>[
    [{
        "timestamp": 1474088400000,
        "errors": 1018831,
        "errorTotal": 72400021,
        "errorTotal2": 0.013022892930509898,
        "business": 4814994,
        "breakdown": [{
            "type": "type1",
            "count": 603437
        }, {
            "type": "type2",
            "count": 256187
        }]
    }]
]
</code></pre>

<p>All I am trying to do is add a new key pair under "breakdown", specifically "type3", so the JSON object looks like this...</p>

<pre><code>[
    [{
        "timestamp": 1474088400000,
        "errors": 1018831,
        "errorTotal": 72400021,
        "errorTotal2": 0.013022892930509898,
        "business": 4814994,
        "breakdown": [{
            "type": "type1",
            "count": 603437
        }, {
            "type": "type2",
            "count": 256187
        }, {
            "type": "type3",
            "count": 4533
        }]
    }]
]
</code></pre>

<p>I thought treating it like key pairs in a list would be the way to go but it doesn't seem to be working. Can anyone point me in the right direction ?
Many thanks in advance!</p>

<p>First, you should read the json into Python objects:</p>

<pre><code>data = json.loads(jsonstring)
</code></pre>

<p>Then get to the object to be modified. The data looks like <code>[ [ {... 'breakdown': ...} ] ]</code>, so it is a list of lists of dictionaries. I guess you want all of them:</p>

<pre><code>for d in data:
    for dd in d:
        d['breakdown'].append({"type": "type3", "count": 4533})
</code></pre>

<p>Then convert it back to json:</p>

<pre><code>update_json = json.dumps(data)
</code></pre>

python json python-2.7