python之json模块

描述

该模块提供了处理JSON(JavaScript Object Notation)格式的方法。

指导文献

链接:json — JSON encoder and decoder — Python 3.7.13 documentation

使用规则

JSON为一个模块,如果需要使用该模块中的方法,需要先进行导入,如下所示:

import json

类型映射

python编码为JSON

python中的类型编码为JSON时,其类型对应如下表所示:

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

JSON解码为python

JSON中的类型解码为python时,其类型对应如下表所示:

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

模块内置方法(V3.7)

  • json.dumps(obj, * , skipkeys=False, ensure_ascii=True, *check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

用途:将python对象编码为JSON格式的字符串。

返回值:返回JSON字符串。

       其中,

       参数obj -- 需要编码的python对象。

       参数skipkeys -- 如果该参数为True,则dict中的keys不属于基本类型(str, int, float, bool, None)将被跳过,而不是抛出TypeError异常。

       参数ensure_ascii -- 如果该参数为True,当obj中包含了非ASCII码(例如:中文),则默认输出ASCII码;如果该参数为False,则当obj中包含了非ASCII码,则此类字符在 JSON 字符串中进行转义。

       参数check_circular -- 如果该参数为False,则跳过容器类型的循环引用检查,循环引用将导致溢出错误(或更糟的情况)。

       参数allow_nan -- 如果该参数为False,那么序列化超出范围的浮点值(nan、inf、-inf),将严格遵守 JSON 规范,而不是使用JavaScript等价物(nan, Infinity, -Infinity)。

       参数indent-- 如果是一个非负整数,那么JSON数组元素和对象成员将使用该缩进级别进行打印。缩进级别0只会插入换行符。None是最紧凑的表示。

        参数separators -- 是分隔符的意思,参数意思分别为不同dict项之间的分隔符和dict项内key和value之间的分隔符,把:和,后面的空格都除去了。

        参数default -- default(obj)是一个函数,它应该返回一个可序列化的obj版本或引发类型错误。默认值只会引发类型错误。

        参数sort_keys -- 如果该参数为True,是告诉编码器按照字典排序(a到z)输出。如果是字典类型的python对象,就把按照字典的key进行排序。

例:

>>> import json
# 例1
>>> test = {"name":"小七", "age":18} #定义一个字典
>>> print(type(test))
<class 'dict'>  #类型为字典
>>> res = json.dumps(test)
>>> print(res, "type is %s" %(type(res)))
{"name": "\u5c0f\u4e03", "age": 18} type is <class 'str'> #res的类型是JSON字符串,且中文也转换为ASCII码
>>> res = json.dumps(test, ensure_ascii = False) #将ensure_ascii设置为False,含有中文的将按照中文输出
>>> print(res, "type is %s" %(type(res)))
{"name": "小七", "age": 18} type is <class 'str'> #res的类型是JSON字符串,且中文按照输出而不是ASCII码
​
#例2
>>> test = {(1, 2):18}
>>> res = json.dumps(test)   #因为dict的key为元组,不是基本类型,且skipkeys默认为False,因此抛出TypeError
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    res = json.dumps(test)
TypeError: keys must be str, int, float, bool or None, not tuple
>>> res = json.dumps(test, skipkeys = True)  #将skipkeys设置为True,不会抛出TypeError
>>> print(res)
{} #虽然skipkeys = True不会抛出TypeError,但是json.dumps返回的数据为{},该类型也为str
​
#例3
>>> test = {2:3, 1:4}
>>> res = json.dumps(test)
>>> print(res)
{"2": 3, "1": 4}  #输出结果,按照字典的顺序输出,且key虽然是数字,也转换成了字符串
>>> res = json.dumps(test, sort_keys=True)
>>> print(res)
{"1": 4, "2": 3}  #输出结果,基于字典的key进行排序后输出。
  • json.dump(obj,fp, * , skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

用途:将python对象编码为JSON格式的流到fp中。

返回值:无。

        其中,

        参数fp -- 文件。

        其他参数与json.dumps()含义一致。

例:

>>> import json
#例1
>>> test = {"name":"小七", "age":18} #定义一个字典
>>> print(type(test))
<class 'dict'>  #类型为字典
>>> with open("hello.txt", "w") as file: 
    json.dump(test, file)   #将JSON格式的流写入到文件中
​
>>> with open("hello.txt", "r") as file:
    print(file.read())  #读取文件
​
{"name": "\u5c0f\u4e03", "age": 18}  #JSON的输出结果,因为将ensure_ascii默认为True
>>> 
​
#例2
>>> test = {"name":"小七", "age":18} #定义一个字典
>>> print(type(test))
<class 'dict'>  #类型为字典
>>> with open("hello.txt", "w") as file: 
    json.dump(test, file, ensure_ascii= False)  #将JSON格式的流写入到文件中
​
>>> with open("hello.txt", "r") as file:
    print(file.read(), "type is %s", %type(file.read()))  #读取文件
​
{"name": "小七", "age": 18} type is <class 'str'>  #JSON的输出结果
>>> 
  • json.load(fp, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

用途:将JSON字符串的流解码为python对象。

返回值:解码后的python对象。

        其中,

        参数fp -- 需要解码的JSON字符串的文件。

例:

>>> import json
>>> test = {"name":"小七", "age":18} #定义一个字典
>>> print(type(test))
<class 'dict'>  #类型为字典
>>> with open("hello.txt", "w") as file: 
    json.dump(test, file, ensure_ascii= False)  #将JSON格式的流写入到文件中
​
>>> with open("hello.txt", "r") as file:
    res = json.load(file)
    print(res, "type is %s" %type(res))
​
{"name": "小七", "age": 18} type is <class 'dict'>  #JSON的输出结果,虽然与json.dump中的例2输出的字符串一致,但是其类型是不一样的,json.load()的类型是python的类型。注意dump和load并未要求要配对使用。
>>> 
  • json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

用途:将JSON字符串解码为python对象。

返回值:解码后的python对象。

        其中,

        参数s -- 需要解码的JSON字符串。

例:

>>> import json
>>> test = {"name":"小七", "age":18} #定义一个字典
>>> print(type(test))
<class 'dict'>  #类型为字典
>>> jsonStr = json.dumps(test, ensure_ascii=False)
>>> print(jsonStr, "type is %s" %type(jsonStr))
{"name": "小七", "age": 18} type is <class 'str'> #输出结果,类型为str
>>> pythonType = json.loads(jsonStr)
>>> print(pythonType, "type is %s" %type(pythonType)) #输出结果,类型为dict

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

5G加油站

你的鼓励是创造的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值