Hangfish Hangfish - 1 month ago 7
JSON Question

Several values in a nested json dictionary/string in Python

I'm attempting to build a json file that within a nested dictionary saves several sets of coordinates. These are supposed to be frameworks for json strings that will be variables in a node in Node-Red and then used by python scripts, here is an example of the strings:

koordinatstring = {
"Coordinates":
{
"AllCoordinates":
{
"FirstCordinates":
{
"X": "1",
"Y": "1"
}
"SecondCordinates":
{
"X": "2",
"Y": "2"
}
}
}
}


This does not work. However this structure works when just looking at a single set of variables.

koordinatstring = {
"Coordinates":
{
"AllCoordinates":
{
"FirstCordinates":
{
"X": "1",
"Y": "1"
}
}
}
}


My question is, how should I the string in the format the first example to actually be able to accept both values when I use them in Node-Red?

Answer

Add a comma after "FirstCordinates" block, like this:

"FirstCordinates":
{
    "X": "1",
    "Y": "1"
},

Further explanation: In Python, you declare dictionary like this:

my_dict = { "key1": "value1" }

If you have multiple key/value pairs, you separate them using comma.

my_dict = { 
    "key1": "value1",
    "key2": "value2" 
}

Instead of having a string "value" as a value for key1, it can be another dictionary!

my_dict = { 
    "key1": 
    {
        "subkey1": "subvalue1"
    },
    "key2": "value2" 
}

But always, after a key/value pair, there has to be comma (if another key/pair follows it, no need for comma if it's the last one, but it doesn't hurt).

Instead of having a string or a dictionary as a value (as we showed now), the value can be a number, a list or some other type.