json.loads() 将Json 字符串解码成Python对象: json到字典
json.load 将文件中的json格式转化成Python对象提取出来
json.dumps()  将Pyhon对象编码成Json字符串:字典到json
json.dump() 将Python中的对象转化成Json储存到文件

 

1 json.loads()  将json格式的数据转化为字典类型

# -*- coding:utf-8 -*-

import json

json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'

json_dict = json.loads(json_str)

print("====转之前====")
print("type(json_str)", type(json_str))
print(json_str)
print("====转之后====")
print("type(json_dict)", type(json_dict))
print(json_dict)

2 json.load()  从文件中读取json类型数据,并转化为字典类型

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

# json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'
# 文件中内容和json_str是一样的
with open("file_str.txt", mode="r", encoding="utf-8") as file:
    json_dict = json.load(file)

print("====转之前====")
print("type(file", type(file))
print(file)
print("====转之后====")
print("type(json_dict)", type(json_dict))
print(json_dict)

3 json.dumps()  将Python中特定类型进行字符串格式化操作,即转换为Json格式的数据

其实就类似于直接用str()进行强制转换,但是dumps()转了之后,有中文的被编码了,那这个时候如果有中文的话,在转换的时候,加ensure_ascii=False

# -*- coding:utf-8 -*-

import json

json_dic = {"token":"dasgdhasdas", "status":0, "data":{"name":"隔壁老王", "password":123456}, "author":None}
json_str = json.dumps(json_dic)
json_str_ensure_ascii = json.dumps(json_dic, ensure_ascii=False)
json_str_str = str(json_dic)

print("====转之前====")
print("type(json_dic)", type(json_dic))
print(json_dic)

print("====转之后====")
print("type(json_str)", type(json_str))
print("type(json_str_ensure_ascii)", type(json_str_ensure_ascii))
print(json_str_ensure_ascii)
print(json_str)
print("====使用str====")
print("type(json_str_str)", type(json_str_str))
print(json_str_str)

4 json.dump()  字典类型转化为 Json字符串格式,写入到文件中

# -*- coding:utf-8 -*-

import json

json_dic = {"token":"dasgdhasdas", "status":0, "data":{"name":"隔壁老王", "password":123456}, "author":None}
with open("file.txt", mode="a", encoding="utf-8") as file:
    json.dump(json_dic, file, ensure_ascii=False, indent=2)

 

其他:

 

json.dumps(obj,   # 待转化的对象
           skipkeys=False,  # 默认值是False,若dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key 
           ensure_ascii=True,  # 默认是ASCII码,若设置成False,则可以输出中文
           check_circular=True,  # 若为False,跳过对容器类型的循环引用检查
           allow_nan=True,  # 若allow_nan为假,则ValueError将序列化超出范围的浮点值(nan、inf、-inf),严格遵守JSON规范,而不是使用JavaScript等价值(nan、Infinity、-Infinity)
           cls=None, 
           indent=None, # 参数根据格式缩进显示,表示缩进几个空格
           separators=None,   # 指定分隔符;包含不同dict项之间的分隔符和key与value之间的分隔符;同时去掉`: `
           encoding="utf-8",  # 编码
           default=None, # 默认是一个函数,应该返回可序列化的obj版本或者引发类型错误;默认值是只引发类型错误
           sort_keys=False,  # 若为False,则字典的键不排序;设置成True,按照字典排序(a到z) 
           **kw)

 

information4 = {
     name :  小明 ,
     age : 18,
     skills :  python ,
     english :  CET6 ,
     major :  会计 ,
     address :  深圳 
}

information5 = json.dumps(information4, ensure_ascii=False)   # 
# 使用json.dump;json数据一定是双引号

with open("information_1_to_json.json", "w", encoding= utf-8 ) as f:
    # json.dump(dic_, f) # 全部写入一行数据,不换行
    json.dump(information,   # 待写入数据
              f, # File对象
              sort_keys=True,  # 键的排序
              ensure_ascii=False)  # 显示中文

 

# 使用json.load

with open("information_to_json.json",encoding="utf-8") as f:
    json_to_dict = json.load(f)  # json转成字典

print(json_to_dict)
information1 = {
     name :  小明 ,
     age : 18,
     address :  shenzhen 
}
# 字典转成json数据
information3 = json.dumps(information1,ensure_ascii=False)

information11 = json.loads(information3)  # json转成字典数据
print(information11)

 

其他当request 请求返回的是json:

import json

withe open('chandashi_resutl.json', 'w', encoding='utf-8') as f:
    json.dump(response.json(), f, ensure_ascii=False)

 

 

参考:

Python处理JSON数据,建议收藏! (qq.com)

Python json中一直搞不清的load、loads、dump、dumps、eval (qq.com)

 

posted on 2022-08-09 23:47  雨点点  阅读(137)  评论(0编辑  收藏  举报