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>You can try something similar to below;</p>

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

    ]

    def insertOrUpdate(updatedObj):
            existing = [x for x in myList if x['provider'] == updatedObj['provider']]
            if len(existing) == 1:
                    existing[0]['url'] = updatedObj['url']
            else:
                    myList.append(updatedObj)

    insertOrUpdate({"name": "Name 1", "provider": "Provider 1", "url": "updated Url", "source": "URL"})
    insertOrUpdate({"name": "Name X", "provider": "Provider X", "url": "new Url", "source": "URL"})
</code></pre>

python json