Flask python json解析

2024-09-26 18:06:56 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我对烧瓶和Python完全陌生。我正在使用一个API来进行地理编码 我得到了一个json

"info": {
    "copyright": {
      "imageAltText": "\u00a9 2015 MapQuest, Inc.", 
      "imageUrl": "http://api.mqcdn.com/res/mqlogo.gif", 
      "text": "\u00a9 2015 MapQuest, Inc."
    }, 
    "messages": [], 
    "statuscode": 0
  }, 
  "options": {
    "ignoreLatLngInput": false, 
    "maxResults": -1, 
    "thumbMaps": true
  }, 
  "results": [
    {
      "locations": [
        {
          "adminArea1": "US", 
          "adminArea1Type": "Country", 
          "adminArea3": "", 
          "adminArea3Type": "", 
          "adminArea4": "", 
          "adminArea4Type": "County", 
          "adminArea5": "", 
          "adminArea5Type": "City", 
          "adminArea6": "", 
          "adminArea6Type": "Neighborhood", 
          "displayLatLng": {
            "lat": 33.663512, 
            "lng": -111.958849
          }, 
          "dragPoint": false, 
          "geocodeQuality": "ADDRESS", 
          "geocodeQualityCode": "L1AAA", 
          "latLng": {
            "lat": 33.663512, 
            "lng": -111.958849
          }, 
          "linkId": "25438895i35930428r65831359", 
          "mapUrl": "http://www.mapquestapi.com/staticmap/v4/getmap?key=&rand=1009123942", 
          "postalCode": "", 
          "sideOfStreet": "R", 
          "street": "", 
          "type": "s", 
          "unknownInput": ""
        }
      ], 
      "providedLocation": {
        "city": " ", 
        "postalCode": "", 
        "state": "", 
        "street": "E Blvd"
      }
    }
  ]
}

现在我在做这个

^{pr2}$

这将打印上面显示的所有数据。我需要从有结果的地点得到latlng阵列。我试过了 data.get("results").get("locations")和成百上千个这样的组合,但我还是不能让它工作。我基本上需要将lat和long存储在会话变量中。感谢任何帮助


Tags: comfalsehttpstreetget烧瓶resultsinc
3条回答

我的意见总结如下:

您可以将数据用作dictlistdict。在

dictlist的快速引用:

A dictionary’s keys are almost arbitrary values.

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

official docs about stdtypes

假设您只有一个位置,如您的示例所示:

from __future__ import print_function

import json

r = ...
data = json.loads(r)

latlng = data['results'][0]['locations'][0]['latLng']
latitude = latlng['lat']
longitude = latlng['lng']

print(latitude, longitude)  # 33.663512 -111.958849

data.get("results")将返回一个列表类型的对象。由于list对象没有get属性,因此不能data.get("results").get("locations")

根据您提供的json,您可以这样做:

data.get('results')[0].get('locations') # also a list

这将给你阵列。现在您可以得到latlng,如下所示:

^{pr2}$

相关问题 更多 >

    热门问题