【Python/Json】从Java SpringBoot程序提供的Rest服务里获取Json串并解读
2022/2/15 9:11:41
本文主要是介绍【Python/Json】从Java SpringBoot程序提供的Rest服务里获取Json串并解读,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
关于如何用SpringBoot程序提供Json串请参考:https://www.cnblogs.com/heyang78/p/15894885.html
【获取部分】
使用以下三行程序就能访问到Rest服务:
request=urllib.request.Request('http://localhost:8080/fetchJson') with urllib.request.urlopen(request) as response: data=response.read()
而要将data变成可读的json还需要下面一步:
jsonStr=data.decode()
这样就获得了想要的json串:
{"status":true,"class":{"id":1,"name":"大一","students":[{"id":1,"name":"刘德华"},{"id":2,"name":"郭富城"},{"id":3,"name":"张学友"},{"id":4,"name":"黎明"}]}}
而解读利用字典就可以了,比如获得上面这个串的students节点,可以这么做:
root=json.loads(jsonStr) students=root['class']['students']
而要取得每个学生的姓名,可以这样做:
for stu in students: print(stu['name'])
直白而快捷,极易上手。
最终将全部程序程序分享如下:
#encoding=utf-8 import urllib.request import json class JsonReader: def __init__(self,url): self.url=url def read(self): request=urllib.request.Request(self.url) with urllib.request.urlopen(request) as response: data=response.read() jsonStr=data.decode() # 获取根节点 root=json.loads(jsonStr) students=root['class']['students'] for stu in students: print(stu['name']) url='http://localhost:8080/fetchJson' reader=JsonReader(url) reader.read();
输出:
C:\hy\py>python 03-jsonReader.py 刘德华 郭富城 张学友 黎明
END
这篇关于【Python/Json】从Java SpringBoot程序提供的Rest服务里获取Json串并解读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?