2024-06-08_python操作json

前言

  • python操作json就是把json文件或json字符串转换为python内部的数据类型,通常是字典
  • 可以使用内置的json模块来实现对json的操作

1. json文件转换为python字典

import json
with open('json.file') as f:
  data = json.load(f)

2. json字符串转换为python字典

import json
data = json.loads(json_str)

3. python字典转换为json文件

  • indent:用于设置输出的 JSON 字符串的缩进空格数
  • sort_keys:用于设置是否要对字典的键进行排序。
  • ensure_ascii:用于设置是否仅使用 ASCII 字符。
  • escape_forward_slashes:用于设置是否要转义正斜杠 /。
import json
with open('json.file') as f:
  json.dump(data, f, indent=4)

4. json.dump写入文件后显示\u解决办法

  • 增加ensure_ascii=False命令即可


    image.png
import json
with open('json.file') as f:
  json.dump(data, f, indent=4, ensure_ascii=False)

5. python字典转换为json字符串

import json
with open('json.file') as f:
  json.dumps(data, f, indent=4)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容