【发布时间】:2017-02-08 00:01:25
【问题描述】:
我正在从 URL 下载一些 JSON:
from urllib.request import Request, urlopen
import json
url = 'xyz'
r = Request(url, headers={'User-Agent':'Mozilla/5.0'})
weburl = urlopen(r)
dat = weburl.read()
encoding = weburl.info().get_content_charset('utf-8')
j = json.loads(data.decode(encoding))
print(j)
这会产生类似:
{
"foo":123,
"bar":4,
"c640103":[5,"xyz", 85.6 ... ],
"c63f456":[8,"pyz", 45.6 ... ],
"c63fdfd":[2,"xhk", 42.8 ... ],
"c64088a":[9,"vyi", 61.1 ... ],
"c63eb0c":[1,"xeq", 25.4 ... ]
}
可以看出,bar 之后的键有点……奇怪。我不知道事先知道它们是什么或可能是什么。
如何获取 foo 作为变量,然后获取 bar 作为变量,然后获取每个不可靠的键及其数组?
我想得到这样的东西:
foo = j['foo']
bar = j['bar']
wonky_keys = j['wonky_keys']
for i in wonky_keys:
print(i[0]) //5
print(i[1]) //xyz
...
【问题讨论】:
-
j是一本字典。你可以循环j.items() -
@cricket_007 谢谢,这正是我需要的……但我是一个 python 新手,所以甚至不知道如何使用它!
标签: python json python-3.x