python 操作json数据
2022/6/2 1:21:49
本文主要是介绍python 操作json数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
简介
JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式,通常是以键值对的方式呈现,其简洁和清晰的层次结构使得JSON成为理想的数据交换语言,而在Python中处理JSON格式的模块有json和pickle两个。
json模块和pickle都提供了四个方法:dumps, dump, loads, load 序列化:将python的数据转换为json格式的字符串 反序列化:将json格式的字符串转换成python的数据类型
dumps与loads
dumps与loads主要是针对于json数据的处理,更加关注于数据类型本身。
json_data = {'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}} content = json.dumps(json_data) print(content) print(type(content)) content = json.loads(content) print(content) print(type(content))
{"test": {"test1_1": 1}, "test2": {"test2_2": {"test2_3": 2}}, "test3": {"test3_2": {"test3_3": {"test3_4": 3}}}} <class 'str'> {'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}} <class 'dict'>
dump与load
dump与load主要是针对于json文件的处理。
test.json
{ "test":{ "test1_1":1 }, "test2":{ "test2_2":{ "test2_3":2 } }, "test3":{ "test3_2":{ "test3_3":{ "test3_4":3 } } } }
读取json数据并写入新的json数据
import json, os JSON_PATH = os.path.join(os.path.dirname(__file__), 'test.json') JSON_PATH2 = os.path.join(os.path.dirname(__file__), 'test2.json') with open(JSON_PATH, mode='r', encoding='utf8') as r_f: content = json.load(r_f) print(content) print(type(content)) with open(JSON_PATH2, mode='w', encoding='utf-8') as w_f: json.dump(content, w_f, indent=True)
{'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}} <class 'dict'>
总结
json.dumps、json.dump是将python数据类型转换为json数据的字符串类型。
json.loads、json.load是将json数据的字符串类型转换为python数据类型,一般为字典
json.dumps与json.loads主要是针对于json数据的处理,更加关注于数据类型本身。
json.dump与json.load主要是针对于json文件的处理。
这篇关于python 操作json数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist