首页 > 解决方案 > 如何提取存储在 JSON 文件中的二维数组?

问题描述

我有以下代码用于打开上述 json 文件并提取数据。但是,我只想要坐标数据,但代码给了我以下错误。 TypeError: string indices must be integers.

我将如何打印出坐标数据?

{
"type": "Polygon",
"coordinates": [
    [
        [
            -5.84731,
            60.5832
        ],
        [
            -5.93843,
            60.5832
        ],
        [
            -2.39097,
            60.5832
        ],
        [
            -2.39097,
            60.5843
        ],
        [
            -2.75097,
            60.5823
        ]
    ]
]
}



import json

f = open('allData.json')
data = json.load(f)
print(data['type']['coordinate'])

f.close()

标签: pythonarraysjson

解决方案


你只需要调用坐标

import json

f = open('allData.json')
data = json.load(f)
print(data['coordinates'])
f.close()

输出

[[[-5.84731, 60.5832], [-5.93843, 60.5832], [-2.39097, 60.5832], [-2.39097, 60.5843], [-2.75097, 60.5823]]]

推荐阅读