【发布时间】:2016-10-25 11:31:18
【问题描述】:
我是 JSON 新手,我正在使用 Python 从 JSON 数据中提取值。我正在使用另一个带有 cURL 的 shell 脚本获取 JSON 数据。
这是我从 shell 脚本(称为 test.sh)的 JSON 输出:
{"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"}}
我想将所有“Country”值和“count”值打印成这样的:
AU 417
BG 7
CA 198
...
为了做到这一点,我创建了一个循环来获取和打印所有需要的值,但是我得到了这个错误:
AttributeError: 'str' object has no attribute 'read'
这是我的python代码:
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']
我在这里错过了什么吗?
任何帮助将不胜感激, 非常感谢
【问题讨论】:
-
如果你有一个字符串,你应该使用
json.loads。另请注意,您的输出实际上不是有效的 JSON(或者,它是多个 JSON 对象,我认为json要么只解析第一个对象,要么向您抱怨)。 -
我觉得Python的json很严格。尝试在引号之间加上真假和数字
-
@Goufalite true、false、数字等都是有效的JSON值
-
@Goufalite 反正这不是问题。
-
是的,因为您没有一个有效的 JSON 对象。如果要返回多个对象,请将它们放入一个数组中(即以
[开头,以]结尾,每个对象之间以,结尾,就像Python 列表一样)。或loads一次一行/一个对象。