Python中JSON库的用法(load、loads、dump、dumps)

前言:JSON格式是一种轻量级别的数据交换格式,容易被人识别和机器用来解析,它的全称叫做 JavaScript Object Notation。python json模块提供了和pickle python相似的API接口,可以将内存中的Python对象转换为一个串行化表示,被叫作json。json最广泛的应用于AJAX应用中的WEB服务器和客户端之间的通信,也可以用于其它程序的应用中。无论是利用python开发还是其它语言开发的很多大中型网都在采用json格式来交换数据,Python标准库中有一个专门解析这个数据格式的模块就叫做:json模块。

1.Python中加载JSON
使用loads(string):作用将string类型转为dict字典或dict链表

# 加载配置,configuration_path:配置文件路径
def load_conf(configuration_path):
    with open(configuration_path, 'r') as f:
        string = f.read()
    return json.loads(string)

使用load(file_stream):作用从文件流直接读取并转换为dict字典或dict字典链表

# 加载配置,configuration_path:配置文件路径
def load_conf(configuration_path):
    with open(configuration_path, 'r') as f:
        data = json.load(f)
    return data

2.Python写入JSON
使用dumps():将可以转换为json对象的对象转换为String,然后可通过字符流或字节流写入文件

 def save_conf(confiuration_path, pre_trans_obj):
    #先用dunps转为string,然后字符流写入
    #ensure_ascii=False, 减少乱码
    json_string = json.dumps(pre_trans_obj, ensure_ascii=False)
    with open(confiuration_path,'w') as f:
        f.write(json_string)

使用dump():将可转为json对象的对象直接写入文件(将两个步骤结合成一个步骤)

def save_conf(confiuration_path, pre_trans_obj):
    with open(confiuration_path,'w') as f:
        json.dump(pre_trans_obj, f, ensure_ascii=False)

3.写入时中文乱码
写入时可能遇到两种中文乱码问题:
(1)显示ASCII码,情况如下:
在这里插入图片描述
原因是,dumps或dump编码时使用了ASCII吗编码中文,只需要在dumps或dump参数中添加参数:ensure_ascii=False,将ascii编码关闭即可。
(2)显示未知字符,情况如下:
在这里插入图片描述
原因是,存入的json文件默认编码为ANSI,而VsCode(IDE)以UTF-8格式打开,所以会出现这样的错误,其他的写入也可能出现类似的问题,检查是否因为这样的问题,用记事本打开文件,显示如下:(注意右下角)
在这里插入图片描述
解决方法:使用open函数时指定编码格式utf-8,即添加参数:encoding=‘utf-8’,完整代码如下:

 def save_conf(confiuration_path, pre_trans_obj):
    #先用dunps转为string,然后字符流写入
    #ensure_ascii=False, 减少乱码
    json_string = json.dumps(pre_trans_obj, ensure_ascii=False)
    with open(confiuration_path,'w',encoding='utf-8') as f:
        f.write(json_string)

注意:任何时候都应注意打开文件的格式,比如ide会默认设置为GBK等等,所以读取、写入文件都应使用统一格式。同理:在Web开发时Request和Response也是如此。

猜你喜欢

转载自blog.csdn.net/weixin_44275820/article/details/108276315
今日推荐