我是JSON的新手,正在使用Python从JSON数据中提取值.我正在使用另一个带有cURL的shell脚本来获取JSON数据.
I'm new to JSON and I'm working on extracting values from JSON data using Python. I'm getting the JSON data using another shell script with cURL.
这是我从shell脚本(称为test.sh)输出的JSON:
Here is my JSON output from the shell script (Called test.sh):
{"preview":true,"offset":0,"result":{"Country":"AU","count":"417"}} {"preview":true,"offset":1,"result":{"Country":"BG","count":"7"}} {"preview":true,"offset":2,"result":{"Country":"CA","count":"198"}} {"preview":true,"offset":3,"result":{"Country":"CH","count":"1"}} {"preview":true,"offset":4,"result":{"Country":"CN","count":"3"}} {"preview":true,"offset":5,"result":{"Country":"CR","count":"1"}} {"preview":true,"offset":6,"result":{"Country":"DE","count":"148"}} {"preview":true,"offset":7,"result":{"Country":"DK","count":"1"}} {"preview":true,"offset":8,"result":{"Country":"FI","count":"1"}} {"preview":true,"offset":9,"result":{"Country":"FR","count":"1052"}} {"preview":true,"offset":10,"result":{"Country":"GB","count":"1430"}} {"preview":true,"offset":11,"result":{"Country":"HK","count":"243"}} {"preview":false,"offset":12,"lastrow":true,"result":{"Country":"VG","count":"54"}}我想将所有国家/地区"值和计数"值打印为以下内容:
I want to print all the "Country" values and the "count" values to something like this:
AU 417 BG 7 CA 198 ...为此,我创建了一个循环以获取并打印所有需要的值,但出现此错误:
In order to do so, I created a loop to fetch and print all the needed values but I get this error:
AttributeError: 'str' object has no attribute 'read'这是我的python代码:
This is my python code:
import subprocess import json import sys import subprocess answer = subprocess.check_output(['./test.sh']) #test.sh contains the cURL command json_obj = json.load(answer) for i in json_obj['result']: print i['Country'] print i['count']我在这里想念东西吗?
任何帮助,我们将不胜感激, 非常感谢
Any help would be appreciated, Thank you very much
推荐答案请将代码保存到test.py,将数据保存到test.json.
Please save the code into test.py and data into test.json.
test.py
import json with open('/tmp/test.json') as f: for i in f: data = json.loads(i) print("{Country} {count}".format(**data["result"]))test.json
$ python test.py AU 417 BG 7 CA 198 CH 1 CN 3 CR 1 DE 148 DK 1 FI 1 FR 1052 GB 1430 HK 243 VG 54
您也可以在编中尝试它:
You can also try it in your prog:
for i in answer: data = json.loads(i) print("{Country} {count}".format(**data["result"]))更多推荐
使用Python解析和打印JSON数据
发布评论