【问题标题】:Parsing a .json file with Python使用 Python 解析 .json 文件
【发布时间】:2015-12-25 02:22:37
【问题描述】:

有很多关于加载 .json 文件的信息,但我就是不知道问题出在哪里:

我有一个名为 LocationHistory.json 的外部文件,里面有各种坐标。作为参考,数据是这样列出的:

{
    "data" : {
      "items" : [ {
        "kind" : "latitude#location",
        "timestampMs" : "1374870896803",
        "latitude" : 34.9482949,
        "longitude" : -85.3245474,
        "accuracy" : 2149
      }, {
        "kind" : "latitude#location",
        "timestampMs" : "1374870711762",
        "latitude" : 34.9857898,
        "longitude" : -85.3526902,
        "accuracy" : 2016
      }, {
        "kind" : "latitude#location",
        "timestampMs" : "1374870651752",
        "latitude" : 34.9857898,
        "longitude" : -85.3526902,
        "accuracy" : 2016
      }]
   }
 }

我正在尝试解析此信息:

import json

json_file = open ('LocationHistory.json')
json_string = json_file.read() 
json_data = json.loads (json_string) 

locations = json_data ["data"]

for location in locations:
    print location["timestampMS"], location["latitude"], location["longitude"], location["accuracy"]

为什么会出现错误:

第 10 行,在

打印位置["timestampMS"], location["latitude"], location["longitude"], location["accuracy"]

TypeError:字符串索引必须是整数

我能找到的解析 .json 文件的所有信息都解释了我拥有的这种类型的解决方案。我哪里错了?

先谢谢了,我确定这应该是一个简单的错误......

【问题讨论】:

    标签: json python-2.7 parsing


    【解决方案1】:

    您想要迭代数据项:

    locations = json_data["data"]["items"]
    for location in locations:  # now "locations" is a list of dictionaries
        # ...
    

    【讨论】:

    • 非常感谢@alecxe,这解决了我的问题。我能得到的所有信息总是显示与我不同的单个列表,其中包含“数据”和“列表”。感谢您的帮助
    • alecxe,如何将 JSON 数据文件解析为 KML 格式而不是打印出来?谢谢:)
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多