如何利用Python里面的json中的dump()/dumps()函数处理中文

  • 比如说有这样的一个 data={'username':'李华','sex':'male','age':16}现在用json包来处理这条Jason数据:
import json 
data = {'username':'李华','sex':'male','age':16}
in_json = json.dumps(data)
>>>import json 
>>>data = {'username':'李华','sex':'male','age':16}
>>>in_json = json.dumps(data)
>>>in_json
'{"sex": "male", "age": 16, "username": "\\u674e\\u534e"}'
  • 可以看一下dumps()/dump()的文档
def 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):
def 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):
  • 其中dumps()里面的参数解释:

    Serialize obj to a JSON formatted str.(字符串表示的json对象)
    Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
    ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。)
    If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
    If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
    indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
    separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
    default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
    sort_keys:将数据根据keys的值进行排序。
    To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

  • 其中dump()里面的参数解释(只有一个fp参数不一样,其他的都一样):

    Serialize obj as a JSON formatted stream to fp (a.write()-supporting file-like object).

  • 可以用dumps()函数里面的参数进行调整一下,结果就是可以输出中文。
>>>import json 
>>>data = {'username':'李华','sex':'male','age':16}
>>>json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators(',',':'),ensure_ascii=False)
>>>print(json_dic2)
{
    "username":"李华",
    "sex":"male",
    "age":16
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值