Search code examples
pythonjsonpython-3.x

Modify JSON data in Python 3


I am trying to amend the value of a node in my JSON, however, I keep getting "SyntaxError: invalid Syntax"

Every question I've looked at gives the same answer: 1, 2, 3. As do online article (example). Use (in psuedo terms) {jsonvariable}.["{Node Name}"] = {new value} however, this doesn't work, no matter what I try, the Python file refuses to run.

This makes me assume it's my implementation, but perhaps it because these answers are based on Python 2 and I'm (currently) using 3.7.5.

The JSON value I'm trying to update is a second level value, which might make a difference, however, Googling/Searching appears to never bring me to a example with that, and I know that clock.[id+".Status"] = "Finished doesn't work.

The JSON snippet looks like this:

{
    "0c2ad7d1-0fc9-47d5-99a2-2e7c8cff2a3d": {
        "Status": "Finished",
        "Status Time": "2020-05-17 16:48:12.584676",
        "Channel ID": 704635364039589941,
        "Active Player": 1,
        "Message ID": "",
        "Player1": {
            "Name": "Larnu",
            "ID": 357506009675333632,
            "Remaining": "01:00"
        },
        "Player2": {
            "Name": "Dolphin Bot",
            "ID": 357506009675333632,
            "Remaining": "01:00"
        }
    },
    "a370d674-6f1a-41be-86d2-9f8c73ab8ab0": {
        "Status": "Not Started",
        "Status Time": "2020-05-17 16:48:12.584676",
        "Channel ID": 704635364039589941,
        "Active Player": "1",
        "Message ID": "711605974779166730",
        "Player1": {
            "Name": "Larnu",
            "ID": 357506009675333632,
            "Remaining": "01:00:00"
        },
        "Player2": {
            "Name": "Dolphin Alpha",
            "ID": 704635572580253818,
            "Remaining": "01:00:00"
        }
    }
}

And the value I'm trying to change is Status in the a370d674-6f1a-41be-86d2-9f8c73ab8ab0 tree. The relevant part that's erroring is:

                with open("clocks.json","r+") as clocks_file:
                    clocks = json.load(clocks_file)
                    clock = clocks[clockid]
                    clock.['Status'] = "Finished"
                    

clockid would have been set previously (if the Python file ran) with the value a370d674-6f1a-41be-86d2-9f8c73ab8ab0.


Solution

  • If I understand correctly, I think you'll want to get rid of the . before the [. In other words:

    clock['Status'] = 'Finished'
    

    or, without assignment:

    clocks[clockid]['Status'] = 'Finished'