0

I've loaded a JSON file but I'm not able to parse it in order to update or insert values.

The JSON structure is similar to this one:

{
    "nodes": [
        {
            "id": "node1",
            "x": 21.0,
            "y": 8.0
        },
        {
            "id": "node5",
            "x": 3.0,
            "y": 5.0
        }
    ]
}

While my python code to retrieve a node is similar to this:

jsonData = defaultdict(list)
with open('data.json', 'r') as f:
    jsonData = json.load(f)
print jsonData['nodes']['id'] == 'node5'

The error I get is "TypeError: list indices must be integers, not str".

How can I retrieve a node and how can I update it?

2
  • By the way, the JSON you have is broken, the third from last line has a , after the } which shouldn't be there. Commented Mar 25, 2015 at 22:09
  • Thank you, it's my fault but fortunally it's only a bad copy and paste, the original JSON is OK. Commented Mar 25, 2015 at 22:15

2 Answers 2

1

In your JSON, nodes is a list of objects, so you can't try to access elements inside it using a string like you are doing with 'id'.

Instead, you can iterate over it:

with open('data.json', 'r') as f:
    jsonData = json.load(f)

for item in jsonData['nodes']:
    print item['id'], item['x'], item['y']

[Edit] To address your comment:

with open('data.json', 'r') as f:
    jsonData = json.load(f)

jsonData['nodes'] = {e['id']: e for e in jsonData['nodes']}
jsonData['nodes']['node5']['z'] = 12
Sign up to request clarification or add additional context in comments.

2 Comments

thank you Joseph but in this way how can I add a new value to an old node? (Say... I need to add "z"= 12 in the node with id = 'node5'.)
If you don't have any control over the JSON you're reading in, you have two options: one, iterate over all of json['nodes'] and inside the loop, check if the current element is the one you want to modify. Or, better yet, just turn jsonData['nodes'] into a dict itself based on its contents, e.g jsonData['nodes'] = {e['id']: e for e in jsonData['nodes']}
0

This snippet adds a a new value (z=12) to an old node and updates the existing node y

import json
from collections import defaultdict

jsonData = defaultdict(list)
with open('c:/temp/data.json', 'r') as f:
    jsonData = json.load(f)
for item in jsonData['nodes']:
    if  item['id']=='node5':
       item['y'] = 5
       item['z'] = 12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.