简体   繁体   English

使用python访问嵌套对象

[英]Accessing nested objects with python

I have a response that I receive from foursquare in the form of json. 我收到来自foursquare的json响应。 I have tried to access the certain parts of the object but have had no success. 我试图访问对象的某些部分,但没有成功。 How would I access say the address of the object? 我如何访问说对象的地址? Here is my code that I have tried. 这是我尝试过的代码。

url = 'https://api.foursquare.com/v2/venues/explore'

params = dict(client_id=foursquare_client_id,
              client_secret=foursquare_client_secret,
              v='20170801', ll=''+lat+','+long+'',
    query=mealType, limit=100)

resp = requests.get(url=url, params=params)

data = json.loads(resp.text)
msg = '{} {}'.format("Restaurant Address: ", 
data['response']['groups'][0]['items'][0]['venue']['location']['address'])
print(msg)

Here is an example of json response: 这是json响应的示例:

"items": [
      {
        "reasons": {
          "count": 0,
          "items": [
            {
              "summary": "This spot is popular",
              "type": "general",
              "reasonName": "globalInteractionReason"
            }
          ]
        },
        "venue": {
          "id": "412d2800f964a520df0c1fe3",
          "name": "Central Park",
          "contact": {
            "phone": "2123106600",
            "formattedPhone": "(212) 310-6600",
            "twitter": "centralparknyc",
            "instagram": "centralparknyc",
            "facebook": "37965424481",
            "facebookUsername": "centralparknyc",
            "facebookName": "Central Park"
          },
          "location": {
            "address": "59th St to 110th St",
            "crossStreet": "5th Ave to Central Park West",
            "lat": 40.78408342593807,
            "lng": -73.96485328674316,
            "labeledLatLngs": [
              {
                "label": "display",
                "lat": 40.78408342593807,
                "lng": -73.96485328674316
              }
            ],

the full response can be found here 完整的回应可以在这里找到

Your code (at least as far as loading and accessing the object) looks correct to me. 您的代码(至少就加载和访问该对象而言)对我而言是正确的。 I loaded the json from a file (since I don't have your foursquare id) and it worked fine. 我从文件中加载了json(因为我没有您的foursquare ID),所以效果很好。 You are correctly using object/dictionary keys and array positions to navigate to what you want. 您正确使用了对象/字典键和数组位置来导航到所需的对象。 However, you mispelled "address" in the line where you drill down to the data. 但是,您在向下钻取数据的行中拼写了“地址”。 Adding the missing 'a' made it work. 添加缺少的“ a”使其起作用。 I'm also correcting the typo in the URL you posted. 我也正在纠正您发布的URL中的错字。

I answered this assuming that the example JSON you linked to is what is stored in data . 我回答这个问题是假设您链接到的示例JSON是存储在data If that isn't the case, a relatively easy way to see exact what python has stored in data is to import pprint and use it like so: pprint.pprint(data) . 如果不是这种情况, import pprint查看python存储在data确切内容的相对简单的方法是import pprint并像这样使用它: pprint.pprint(data)

You could also start an interactive python shell by running the program with the -i switch and examine the variable yourself. 您还可以通过使用-i开关运行程序来启动交互式python shell,然后自己检查变量。

像这样

addrs=data['items'][2]['location']['address']

data["items"][2]["location"]["address"]

这将为您访问地址。

You can go to any level of nesting by using integer index in case of an array and string index in case of a dict. 如果是数组,可以使用整数索引,而如果是dict,则可以使用字符串索引,从而可以进行任何级别的嵌套。 Like in your case items is an array 就像你的情况是一个数组

#items[int index]
items[0]

Now items[0] is a dictionary so we access by string indexes 现在items [0]是字典,因此我们通过字符串索引进行访问

item[0]['location']

Now again its an object s we use string index 现在再次将其作为对象,我们使用字符串索引

item[0]['location']['address]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM