Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中访问JSON中的元素?_Python_Json - Fatal编程技术网

如何在Python中访问JSON中的元素?

如何在Python中访问JSON中的元素?,python,json,Python,Json,我试图解析JSON中元素的get值 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):

我试图解析JSON中元素的get值

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()
我的json是这样的

{
    "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",
            },
        ],
    },
}
用我的代码,我想去“链接”,得到两个ID。当我有两个身份证时,我会去“合作者”。现在我想得到两个id的“x”和“y”。 但我的问题是,当我试图访问我拥有的“x”和“y”时

TypeError: string indices must be integers
当我打印
print(y['x'])
时,我也有同样的问题。我无法访问y元素


有人知道我的错误吗?我怎样才能得到我的“x”和“y”?

y
只是关键,而不是内容。但是您已经有了一个字典来访问ID,因此不需要内部for循环

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'])