dumping vs loading data into JSON

Viewed 49

I observe the following behaviour:

railnet= '''{
    "nodes": [
        {"data": { "id": 1,"name":"BER" }},
        {"data": { "id": 2,"name": "MUN"}},
        {"data": { "id": 3,"name": "FRA"}}
        ],
    "edges": [
        {"data": { "id": "BER - MUN", "source": "BER", "target": "MUN" }},
        {"data": { "id": "MUN - FRA", "source": "MUN", "target": "FRA" }},
        {"data": { "id": "FRA - BER", "source": "FRA", "target": "BER" }}
    ]
  }'''
railnetJSON = json.loads(railnet)
print(railnetJSON['nodes'])

railnet is a STRING. So far everything all right.

But waht if railnet is a dict?:

    railnet= {
    "nodes": [
        {"data": { "id": 1,"name":"BER" }},
        {"data": { "id": 2,"name": "MUN"}},
        {"data": { "id": 3,"name": "FRA"}}
        ],
    "edges": [
        {"data": { "id": "BER - MUN", "source": "BER", "target": "MUN" }},
        {"data": { "id": "MUN - FRA", "source": "MUN", "target": "FRA" }},
        {"data": { "id": "FRA - BER", "source": "FRA", "target": "BER" }}
    ]
  }
print(type(railnet)) # ->dict
railnetJSON = json.dumps(railnet) # -> no error here
print(railnetJSON['nodes']) # -> error here

the line

railnetJSON = json.dumps(railnet)

works but the last line gives:

TypeError: string indices must be integers

The question is why I can dump the dictionary into JSON with dumps (no error) but accessing the nodes raises an error. What is the right way to go to have the same behaviour having a variable as string or dict to be passed to JSON.

In other words, if you need to create a JSON object to be passed to another function accepting JSON how is the way to proceed when you have a dictionary?

thanks

after reading here and here and here it seems that the way to go is indeed dumps for dicts.

2 Answers

json.dumps takes an object (in this case a dict) and dumps it to string in JSON format. From there on, it's just a string. If you want to reference keys inside it, you'll need to json.loads it back to a dict.

json.dumps() converts a JSON to a string so you can't access with keys

Related