【问题标题】:Pandas: access values inside .json filePandas:访问 .json 文件中的值
【发布时间】:2020-02-11 07:59:22
【问题描述】:

我正在尝试创建一个循环,让我可以访问 .json 文件(谷歌位置文件)中的值。我上周刚开始学习 Python,所以请多多关照,非常感谢所有帮助!

首先是我的导入列表:

import pandas as pd
import requests
import json

比我打开 .json 文件:

with open('data_may.json', 'r') as fh:
    raw = json.loads(fh.read())
    data = raw['timelineObjects']
data

最后我试图创建一个循环来打印出 latitudeE7 的值:

for locations in data[0:5]:
    print(locations['placeVisit']['location']['latitudeE7'])

这是我收到的错误消息:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-99-a8c46eea2476> in <module>
      1 for locations in data[0:5]:
----> 2     print(locations['placeVisit']['location']['latitudeE7'])

KeyError: 'placeVisit'

我的 .json 文件是这样构造的:

{
  "timelineObjects" : [ {
    "activitySegment" : {
      "startLocation" : {
        "latitudeE7" : 520950336,
        "longitudeE7" : 51250455,
        "sourceInfo" : {
          "deviceTag" : -1547871288
        }
      },
      "endLocation" : {
        "latitudeE7" : 520969498,
        "longitudeE7" : 51162451,
        "sourceInfo" : {
          "deviceTag" : -1547871288
        }
      },
      "duration" : {
        "startTimestampMs" : "1556693508999",
        "endTimestampMs" : "1556693710203"
      },
      "distance" : 652,
      "activityType" : "CYCLING",
      "confidence" : "HIGH",
      "activities" : [ {
        "activityType" : "CYCLING",
        "probability" : 99.11152749237161
      }, {
        "activityType" : "WALKING",
        "probability" : 0.6369730834565008
      }, {
        "activityType" : "RUNNING",
        "probability" : 0.10388160016829592
      } ],
      "waypointPath" : {
        "waypoints" : [ {
          "latE7" : 520950508,
          "lngE7" : 51250495
        }, {
          "latE7" : 520971412,
          "lngE7" : 51164069
        } ]
      }
    }
  }, {
    "placeVisit" : {
      "location" : {
        "latitudeE7" : 520967891,
        "longitudeE7" : 51159244,
        "placeId" : "ChIJOYpLXEFvxkcRtSdOEoh1Lns",
        "address" : "Bemuurde Weerd Oostzijde 1\n3514 AN Utrecht\nNederland",
        "name" : "LSR Landelijk Studenten Rechtsbureau",
        "sourceInfo" : {
          "deviceTag" : -1547871288
        },
        "locationConfidence" : 37.736637
      },
      "duration" : {
        "startTimestampMs" : "1556693710203",
        "endTimestampMs" : "1556713681618"
      },
      "placeConfidence" : "MEDIUM_CONFIDENCE",
      "centerLatE7" : 520969163,
      "centerLngE7" : 51162406,
      "visitConfidence" : 93,
      "otherCandidateLocations" : [ {
        "latitudeE7" : 520967890,
        "longitudeE7" : 51159240,
        "placeId" : "ChIJOYpLXEFvxkcRV2Hp03ASVuI",
        "locationConfidence" : 33.198143
      }, {
        "latitudeE7" : 520968971,
        "longitudeE7" : 51161709,
        "placeId" : "ChIJbeiKCEFvxkcRgiZQno9hikQ",
        "semanticType" : "TYPE_WORK",
        "locationConfidence" : 23.059763
      }, {
        "latitudeE7" : 520968160,
        "longitudeE7" : 51158805,
        "placeId" : "ChIJ-SXmBkVvxkcRtpNT_vTdQEE",
        "locationConfidence" : 1.7593758
      }, {
        "latitudeE7" : 520971045,
        "longitudeE7" : 51162728,
        "placeId" : "ChIJd66UREFvxkcRZJCaM9z3baw",
        "semanticType" : "TYPE_SEARCHED_ADDRESS",
        "locationConfidence" : 0.6827666
      } ],
      "editConfirmationStatus" : "NOT_CONFIRMED"
    }
  }, {
    "activitySegment" : {
      "startLocation" : {
        "latitudeE7" : 520967891,
        "longitudeE7" : 51159244,
        "sourceInfo" : {
          "deviceTag" : -1547871288
        }
      },
      "endLocation" : {
        "latitudeE7" : 520942097,
        "longitudeE7" : 51258010,
        "sourceInfo" : {
          "deviceTag" : -1547871288
        }
      },
      "duration" : {
        "startTimestampMs" : "1556713681618",
        "endTimestampMs" : "1556713939630"
      },
      "distance" : 816,
      "activityType" : "CYCLING",
      "confidence" : "HIGH",
      "activities" : [ {
        "activityType" : "CYCLING",
        "probability" : 99.41448992772163
      }, {
        "activityType" : "WALKING",
        "probability" : 0.43749986739765867
      }, {
        "activityType" : "IN_PASSENGER_VEHICLE",
        "probability" : 0.08513907766062832
      } ],
      "waypointPath" : {
        "waypoints" : [ {
          "latE7" : 520967674,
          "lngE7" : 51158652
        }, {
          "latE7" : 520942306,
          "lngE7" : 51260013
        } ]
      }
    }
  }, {
    "placeVisit" : {
      "location" : {
        "latitudeE7" : 520941602,
        "longitudeE7" : 51258926,
        "placeId" : "ChIJ46vtEE9vxkcRyu8VVfUro2Q",
        "address" : "Lucasbolwerk 18\n3512 EH Utrecht\nNederland",
        "name" : "Lucasbolwerk 18",
        "semanticType" : "TYPE_HOME",
        "sourceInfo" : {
          "deviceTag" : -1547871288
        },
        "locationConfidence" : 62.083218
      },
      "duration" : {
        "startTimestampMs" : "1556713939630",
        "endTimestampMs" : "1556731681066"
      },
      "placeConfidence" : "HIGH_CONFIDENCE",
      "centerLatE7" : 520942021,
      "centerLngE7" : 51257989,
      "visitConfidence" : 95,
      "otherCandidateLocations" : [ {
        "latitudeE7" : 520940870,
        "longitudeE7" : 51259290,
        "placeId" : "ChIJu8CAEE9vxkcRRXzQvpFYiIk",
        "locationConfidence" : 28.85588
      }, {
        "latitudeE7" : 520940508,
        "longitudeE7" : 51258612,
        "placeId" : "ChIJFXCOGk9vxkcRvLD0dAfMEwE",
        "locationConfidence" : 0.79878336
      }, {
        "latitudeE7" : 520943848,
        "longitudeE7" : 51258475,
        "placeId" : "ChIJC9dtF09vxkcR9zOEsPmnHcQ",
        "locationConfidence" : 0.35787553
      }, {
        "latitudeE7" : 520940508,
        "longitudeE7" : 51258612,
        "placeId" : "ChIJx2ucGk9vxkcRF_deiIhd7_k",
        "locationConfidence" : 0.25281402
      } ],
      "editConfirmationStatus" : "NOT_CONFIRMED"
    }
  }, {

如您所见,目前我只是尝试访问 placeVisit 之后的值。

提前谢谢你!

【问题讨论】:

    标签: python json pandas google-maps


    【解决方案1】:

    placeVisit 只是在每秒timelineObjects 项中,你需要检查placeVisit 是否存在:

    import json
    with open('data_may.json', 'r') as fh:
        raw = json.loads(fh.read())
        data = raw['timelineObjects']
    
    
    for locations in data[0:5]:
        if 'placeVisit' in locations:
            print(locations['placeVisit']['location']['latitudeE7'])
        else:
            print("Found activitySegment instead of placeVisit!")
    

    输出:

    Found activitySegment instead of placeVisit!
    520967891
    Found activitySegment instead of placeVisit!
    520941602
    

    【讨论】:

    • 谢谢,这很有道理。我让它工作了。帮了我很多!
    【解决方案2】:

    让我们从 JSON 中有多少上层键开始:

    data = <your-json-dictionary>
    
    # print a list of your top-level keys 
    print(list(data.keys()))
    

    这表明,

    >> ['timelineObjects']
    

    现在让我们看看data['timelineObject']的元素的键

    for timelineObject in a['timelineObjects']:
        print(list(timelineObject.keys()))
    
    >> ['activitySegment']
       ['placeVisit']
       ['activitySegment']
       ['placeVisit']
       ...
    

    但是,在某些嵌套字典中,键 'placeVisit' 不存在。当遇到这些情况时,Python 正在提高 keyError。当在字典中找不到键时,您应该使用 python 的dict.get(key, default_when_key_is_missing) 方法返回默认值。

    for timelineObject in a['timelineObjects']:
        print(timelineObject.get('placeVisit', None))
    

    这将返回您想要的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2017-09-25
      • 2016-11-09
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      相关资源
      最近更新 更多