使用Python解析和打印JSON数据

编程入门 行业动态 更新时间:2024-10-06 16:28:54
本文介绍了使用Python解析和打印JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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数据

本文发布于:2023-11-26 23:30:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Python   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!