在json模块有2个方法,
loads():将json数据转化成dict数据
dumps():将dict数据转化成json数据
load():读取json文件数据,转成dict数据
dump():将dict数据转化成json数据后写入json文件
import json
# a是字典dict
a = {"a": 1, "b": 2, "c": True}
# b是json
b = '{"a": 1, "b": 2, "c": true}'
print(type(a)) #dict
c=json.dumps(a)
print(type(c)) # a转json a的类型是str
# dict字典转json数据
def dict_to_json():
dict = {}
dict['name'] = 'eden'
dict['age'] = 20
dict['sex'] = 'female'
# print(dict) # 输出:{'name': 'eden', 'age': 20, 'sex': 'female'}
j = json.dumps(dict)
print(j) # 输出:{"name": "eden", "age": 20, "sex": "female"}
# json数据转成dict字典
def json_to_dict():
j = '{"name": "eden", "age": 20, "sex": "female"}'
dict = json.loads(s=j)
print(dict)
def dict_to_json_write_file():
dict = {}
dict['name'] = 'eden'
dict['age'] = 20
dict['sex'] = 'female'
print(dict) #{"name": "eden", "age": 20, "sex": "female"}
with open('1.json', 'w') as f:
json.dump(dict, f) # 会在目录下生成一个1.json的文件,文件内容是dict数据转成的json数据
def json_file_to_dict():
with open('1.json', 'r') as f:
dict = json.load(f)
print(dict) #{"name": "eden", "age": 20, "sex": "female"}