python读写json文件

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。Python3 中可以使用 json 模块来对 JSON 数据进行编解码。

Json模块提供了四个功能:dumps、dump、loads、load

  • dumps : 把数据类型转换成字符串
  • dump : 把数据类型转换成字符串并存储在文件中
  • loads : 把字符串转换成数据类型
  • load : 把文件打开从字符串转换成数据类型

1、dumps:将python中的字典转换为字符串

# -*- coding:utf-8 -*-
import json

test_dict = {
    "status":  0 ,
    "msg":  "SUCCESS",
    "data": [{"id"    : 1 ,"name"  : "xiaohong"},
             {"id"    : 2,"name"  : "xiaoming"}]
}
print(test_dict)
print(type(test_dict))
# dumps 将数据转换成字符串
json_str = json.dumps(test_dict,indent=4)
print(json_str)
print(type(json_str))

2、loads:将字符串转换为字典

new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))

3、dump:将数据格式化写入json文件中

with open("record.json", "w") as f:
    json.dump(new_dict, f,indent=4)

4、load:把文件打开,并把字符串变换为数据类型

with open("record.json",'r') as load_f:
    load_dict = json.load(load_f)
print(load_dict)
print(type(load_dict))
print(load_dict['data'])

参考文献:

  1. 菜鸟教程Python3 JSON 数据解析
  2. json的两种数据结构
  3. JSON encoder and decoder

版权声明:本文为yeqiang19910412原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。