【问题标题】:How can I extract a 2D array that is stored in a JSON file?如何提取存储在 JSON 文件中的二维数组?
【发布时间】:2021-11-10 17:28:33
【问题描述】:

我有以下代码用于打开上述 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()

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

    你只需要调用坐标

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

    【讨论】:

      【解决方案2】:
      print(data['type']['coordinate'])
      

      这是首先获取data['type'] = "Polygon",然后对其应用索引['coordinate'],因此您在索引字符串时遇到错误。

      坐标(复数)不是结构中的子类型。你想要data['coordinates']

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 2020-12-19
        • 2016-12-28
        • 2018-05-19
        • 1970-01-01
        相关资源
        最近更新 更多