Python中如何实现json与字典之间的读写转换?

2026-05-27 02:351阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计404个文字,预计阅读时间需要2分钟。

Python中如何实现json与字典之间的读写转换?

在Python中,json表示的是符合JSON语法的字符串格式,可以是单行或多行。它方便地在多种语言中使用,这里介绍的是在Python中,字典(dict)与JSON字符串相互转化的方式。

1. 导入json库pythonimport json

Python中如何实现json与字典之间的读写转换?

在Python中,json指的是符合json语法格式的字符串,可以单行或者多行。

它可以方便的在使用在多种语言中,这里介绍的是在python中的字典(dict)与json字符串相互转化的方式。

1. 导入json包

import json

2. 初始化一个字典数据

dict_ = { 'name': 'Jack', 'age': 22, 'skills': ['Python', 'Java', 'C++', 'Matlab'], 'major': '计算机技术', 'english': '英语六级', 'school': 'WIT' }

3.json.dumps(字典):将字典转为JSON字符串

# 1. json.dumps(字典):将字典转为JSON字符串,indent为多行缩进空格数, # sort_keys为是否按键排序,ensure_ascii=False为不确保ascii,及不将中文等特殊字符转为\uXXX等 json_dict = json.dumps(dict_) print(json_dict)

很明显中文字符被转化了,于是使用:ensure_ascii=False

# 行缩进和键值排序 json_dict_2 = json.dumps(dict_, indent=2, sort_keys=True, ensure_ascii=False) print(json_dict_2)

3.json.loads(json串),将json字符串转化成字典

dict_from_str = json.loads(json_dict) print(dict_from_str) dict_from_str_2 = json.loads(json_dict_2) print(dict_from_str_2)

4.json.dump,把字典转换成json字符串并存储在文件中,结果文件如下图:

with open("write_json.json", "w", encoding='utf-8') as f: # json.dump(dict_, f) # 写为一行 json.dump(dict_, f, indent=2, sort_keys=True, ensure_ascii=False) # 写为多行

5.json.load,从文件打开json数据转换成字典

with open("write_json.json", encoding="utf-8") as f: json_file = json.load(f) print(json_file)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计404个文字,预计阅读时间需要2分钟。

Python中如何实现json与字典之间的读写转换?

在Python中,json表示的是符合JSON语法的字符串格式,可以是单行或多行。它方便地在多种语言中使用,这里介绍的是在Python中,字典(dict)与JSON字符串相互转化的方式。

1. 导入json库pythonimport json

Python中如何实现json与字典之间的读写转换?

在Python中,json指的是符合json语法格式的字符串,可以单行或者多行。

它可以方便的在使用在多种语言中,这里介绍的是在python中的字典(dict)与json字符串相互转化的方式。

1. 导入json包

import json

2. 初始化一个字典数据

dict_ = { 'name': 'Jack', 'age': 22, 'skills': ['Python', 'Java', 'C++', 'Matlab'], 'major': '计算机技术', 'english': '英语六级', 'school': 'WIT' }

3.json.dumps(字典):将字典转为JSON字符串

# 1. json.dumps(字典):将字典转为JSON字符串,indent为多行缩进空格数, # sort_keys为是否按键排序,ensure_ascii=False为不确保ascii,及不将中文等特殊字符转为\uXXX等 json_dict = json.dumps(dict_) print(json_dict)

很明显中文字符被转化了,于是使用:ensure_ascii=False

# 行缩进和键值排序 json_dict_2 = json.dumps(dict_, indent=2, sort_keys=True, ensure_ascii=False) print(json_dict_2)

3.json.loads(json串),将json字符串转化成字典

dict_from_str = json.loads(json_dict) print(dict_from_str) dict_from_str_2 = json.loads(json_dict_2) print(dict_from_str_2)

4.json.dump,把字典转换成json字符串并存储在文件中,结果文件如下图:

with open("write_json.json", "w", encoding='utf-8') as f: # json.dump(dict_, f) # 写为一行 json.dump(dict_, f, indent=2, sort_keys=True, ensure_ascii=False) # 写为多行

5.json.load,从文件打开json数据转换成字典

with open("write_json.json", encoding="utf-8") as f: json_file = json.load(f) print(json_file)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。