编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

第十四天 JSON和Python(第十天)

wxchong 2024-08-25 16:37:52 开源技术 10 ℃ 0 评论

信息有很多种标记的方式。常见的有html,xml等。

JSON也是一种常见的标记方式。最早它用在JavaScript中,后来扩展到其他语言。目前互联网上的API接口,经常返回JSON格式的字符串。因此它成为目前最流行的数据标记方式。

对JSON格式的字符串的Python官方文档:https://docs.python.org/3/library/json.html?highlight=json

JSON基本操作

JSON和Python的数据类型对应表

两种常用的转换,下面用例子说明

JSON格式的字符串->Python的字典或列表对象

Python的字典或列表对象->JSON格式的字符串

import json
import requests

#json格式的字符串,如何转换成python的列表和字典对象

#json格式的字符串1:用大括号,括起来的字符串->python的字典对象
people_string = '''
{
    "people": [
        {
            "name": "John Smith",
            "phone": "615-555-7164",
            "emails": ["john@email.com", "john@work.com"],
            "has_license": false
        },
        {
            "name": "Jane Doe",
            "phone": "560-555-5153",
            "emails": null,
            "has_license": true
        }
    ]
}
'''

#字典json,初始化为python的字典
data=json.loads(people_string)
for person in data['people']:
    del person['phone']

#将python的字典对象,转换成json格式的字符串,indent=2设置可读的缩进
newString=json.dumps(data, indent=2)


#json格式的字符串2:用方括号,括起来的字符串->python的列表对象
people_string="""[
        {"name": "John Smith", "phone": "615-555-7164"},
        {"name": "Jane Doe", "phone": "560-555-5153"}
    ]
"""  
#将json格式的字符串,转换成python的列表对象
data=json.loads(people_string)      

#读取JSON文件
with open("people_read.json") as f:
    data=json.load(f)


#写入JSON文件
with open("people_write.json","w") as f:
    json.dump(data,f,indent=2)



网络API接口

在网络通信时,我们经常需要完成如下操作

API请求数据->JSON格式的字符串->Python的字典或列表对象->操作数据/写入JSON文件

下面用代码,说明具体的操作

import requests
import json

#构造网络请求
host = "https://api.gateio.ws"
prefix = "/api/v4"
headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
url = '/spot/currencies'
query_param = ''

r = requests.request('GET', host + prefix + url, headers=headers)

#将gateio的json格式的字符串,转换成python的list对象
data=json.loads(r.text)      

#写入JSON文件
with open("gateio.json","w") as f:
    json.dump(data,f,indent=2)

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表