【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串并解读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程