Reputation: 421
I'm trying to parse an get value of my elements in my JSON.
import json
f = open('links.json',)
data = json.load(f)
for i in data['jsonObject']['links']:
for y in data['jsonObject']['coordonates']:
if (i['take1'] == y):
point1 = y
if (i['take2'] == y):
point2 = y
print(point1['x'])
print(point1['y'])
print(point2['x'])
print(point2['y'])
f.close()
And my json is like this
{
"jsonObject": {
"coordonates": {
"id1": {
"x": 100,
"y": 60
},
"id2": {
"x": 50,
"y": 100
},
"id3": {
"x": -100,
"y": 20
},
"id4": {
"x": 30,
"y": 10
},
},
"links": [
{
"take1": "id4",
"take2": "id1",
},
{
"take1": "id4",
"take2": "id3",
},
{
"take1": "id3",
"take2": "id2",
},
{
"take1": "id2",
"take2": "id1",
},
],
},
}
With my code, i want to go to "links", get the two ids. When i have my two id, i'm going to "coordonates". And now i want to get the "x" and "y" of the two id. But my problem is when i'm trying to access to the 'x' and 'y' i have
TypeError: string indices must be integers
And when i'm printing print(y['x'])
, i have the same problem. I can't access to the y elements.
Anyone have an idea of my mistake ? And how can i do to get my 'x' and 'y' ?.
Upvotes: 1
Views: 267
Reputation: 42778
y
is only the key, not the content. But you already have a dictionary, to access the ids, so the inner for-loop is not necessary.
with open('links.json') as f:
data = json.load(f)
coordinates = data['jsonObject']['coordonates']
for link in data['jsonObject']['links']:
point1 = coordinates[link['take1']]
point2 = coordinates[link['take2']]
print(point1['x'])
print(point1['y'])
print(point2['x'])
print(point2['y'])
Upvotes: 1