|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 大马强 于 2021-8-20 09:24 编辑
一、什么是json
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。
它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。
JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。
这些特性使JSON成为理想的数据交换语言。 -----来源百度
其实就是字典和字符串之间的转换,在python要额外导入json库 -> import json
二、常用的方法
1.json.loads
json.load 将数据转换成json格式, 字符串->字典
2.json.domps
json.load 将json转换格式成其他格式,字典->字符串
3.json.load
json.load 从文件中读取字符串,变成字典格式
4.json.domp
json.domp 将字典格式变成字符串写入文件中
三、代码案例
- # 设置数据
- data = {
- 'cursor': "-1",
- "offset": "0",
- "orderType": "1",
- "pageNo": "1",
- "pageSize": "20",
- "rid": "R_SO_4_1855995767",
- "threadId": "R_SO_4_1855995767"
- }
- # 将原数据data打印
- print("康康原数据的类型和内容")
- print("data的类型", type(data))
- print("data的内容", data)
- """
- 输出
- 康康原数据的类型和内容
- data的类型 <class 'dict'>
- data的内容 {'cursor': '-1', 'offset': '0', 'orderType': '1', 'pageNo': '1', 'pageSize': '20', 'rid': 'R_SO_4_1855995767', 'threadId': 'R_SO_4_1855995767'}
- """
- # 使用json.dumps()方法,将字典转换成字符串
- print("\n使用json.dumps()方法,将字典转换成字符串")
- a = json.dumps(data)
- print("a的类型", type(a))
- print("a的内容", a)
- """
- 输出
- 使用json.dumps()方法,将字典转换成字符串
- a的类型 <class 'str'>
- a的内容 {"cursor": "-1", "offset": "0", "orderType": "1", "pageNo": "1", "pageSize": "20", "rid": "R_SO_4_1855995767", "threadId": "R_SO_4_1855995767"}
- """
- # 使用json.loads()方法,将字符串转换成字典
- print("\n使用json.loads()方法,将字符串转换成字典")
- b = json.loads(a)
- print("b的类型", type(b))
- print("b的内容", b)
- """
- 输出
- 使用json.loads()方法,将字符串转换成字典
- b的类型 <class 'dict'>
- b的内容 {'cursor': '-1', 'offset': '0', 'orderType': '1', 'pageNo': '1', 'pageSize': '20', 'rid': 'R_SO_4_1855995767', 'threadId': 'R_SO_4_1855995767'}
- """
- # 使用json.dump()方法,将字典转换成字符串,写入文件 json.txt
- print("\n使用json.dump()方法,将字典转换成字符串,写入文件 json.txt")
- with open("json.txt", "w") as fp:
- json.dump(b, fp)
- with open("json.txt") as fp:
- str_1 = fp.read()
- print("str_1的类型", type(str_1))
- print("str_1的内容", str_1)
- """
- 输出
- 使用json.dump()方法,将字典转换成字符串,写入文件 json.txt
- str_1的类型 <class 'str'>
- str_1的内容 {"cursor": "-1", "offset": "0", "orderType": "1", "pageNo": "1", "pageSize": "20", "rid": "R_SO_4_1855995767", "threadId": "R_SO_4_1855995767"}
- """
- # 使用json.load()方法,从文件 json.txt 中读取字符串,变成字典格式
- print("\n使用json.load()方法,从文件 json.txt 中读取字符串,变成字典格式")
- with open("json.txt") as fp:
- str_2 = json.load(fp)
- print("str_2的类型", type(str_2))
- print("str_2的内容", str_2)
- """
- 输出
- 使用json.load()方法,从文件 json.txt 中读取字符串,变成字典格式
- str_2的类型 <class 'dict'>
- str_2的内容 {'cursor': '-1', 'offset': '0', 'orderType': '1', 'pageNo': '1', 'pageSize': '20', 'rid': 'R_SO_4_1855995767', 'threadId': 'R_SO_4_1855995767'}
- """
复制代码
四、学习中,待完善 |
|