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>

<ol>
<li><p>Load the <code>json</code> string</p>

<pre><code>json_data = json.loads(json_string)
</code></pre></li>
<li><p>Iterate over the object and <code>append</code> to the <code>"breakdown"</code> key</p>

<pre><code>for item in json_data:
    for json_dict in item:
        json_dict["breakdown"].append({"type": "type3", "count": 4533})
</code></pre></li>
<li><p>Convert it back to the <code>JSON</code> string</p>

<pre><code>json_string = json.dumps(json_data)
</code></pre></li>
</ol>

python json python-2.7