Python to update JSON file
<p>After googling around and checking some other posts I still haven't found a solution for my issue. </p>

<p>Let me quickly explain what I'm after:</p>

<p>I've got a JSON configuration file with the following syntax:</p>

<pre><code>    [
        {
                "name": "Name 1",
                "provider": "Provider 1",
                "url": "/1",
                "source": "URL"
        },
        {
                "name": "Name 2",
                "provider": "Provider 2",
                "url": "/1",
                "source": "URL 2"
        }

]
</code></pre>

<p>My issue is the key source changes and I've got a script generating these however I'm not able to find a way to update them automatically ideally I would need to tell my python script to look out for "Provider 1" and then update with the new URL for Provider 1 but my JSON format does not include individual keys and hence I need to search via Provider name and update the source.</p>

<p>Hope this makes sense any help appreciated.</p>

<p>Assuming <code>test.json</code> is your json file containing the text you inserted in the question, you can do the following</p>

<pre><code>import json
with open('test.json') as my_file:
    json_content = json.load(my_file)
for ele in json_content:
    print(ele)
</code></pre>

<p>{'name': 'Name 1', 'provider': 'Provider 1', 'source': 'URL', 'url': '/1'}</p>

<p>{'name': 'Name 2', 'provider': 'Provider 2', 'source': 'URL 2', 'url': '/1'}</p>

<pre><code>new_url = 'something. Define it as you want.'
for ele in json_content:
    if ele['provider']=='Provider 1':
        ele['url']=new_url
for ele in json_content:
    print(ele)
for ele in json_content:

print(ele)
</code></pre>

<p>{'name': 'Name 1', 'provider': 'Provider 1', 'source': 'URL', 'url': 'something. Define it as you want.'}
{'name': 'Name 2', 'provider': 'Provider 2', 'source': 'URL 2', 'url': '/1'}</p>

python json