使用Python 3.5.2从URL解析JSON字符串

时间:2016-10-04 21:08:55

标签: python

我正在尝试从JSON(source)打印出值"lat""lon"

{
    "batchcomplete": "",
    "query": {
        "normalized": [
            {
                "from": "venice",
                "to": "Venice"
            }
        ],
        "pages": {
            "32616": {
                "coordinates": [
                    {
                        "globe": "earth",
                        "lat": 45.4375,
                        "lon": 12.33583333,
                        "primary": ""
                    }
                ],
                "ns": 0,
                "pageid": 32616,
                "title": "Venice"
            }
        }
    }
}

这是我应该工作的代码:

import urllib.request as url
import json
import urllib.parse
import ast

request = url.Request('https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&list=&titles=venice')
data = url.urlopen(request).read()
data = data.decode("utf-8")
data = ast.literal_eval(data)
data = json.dumps(data)
array = json.loads(data)
#print(array)
print(array['query']['pages']['32616']['coordinates']['lat'+','+'lon'])

它返回错误:TypeError: list indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:1)

print(array['query']['pages']['32616']['coordinates'][0]['lat'])
print(array['query']['pages']['32616']['coordinates'][0]['lon'])
                                               insert ^

答案 1 :(得分:1)

import requests
import json

r = requests.get('you URL here')
rData = json.loads(r.text, encoding="utf-8")

print(rData['query']['pages']['32616']['coordinates'][0]['lat'])
print(rData['query']['pages']['32616']['coordinates'][0]['lon'])