当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python json.dumps()用法及代码示例


JSON的完整形式是JavaScript Object Notation。这意味着将使用编程语言的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过名为内置的软件包支持JSONjson。要使用此函数,我们导入json用Python脚本打包。 JSON中的文本是通过带引号的字符串完成的,其中包含了键-值映射中的值{ }。它类似于Python中的字典。

注意:有关更多信息,请参阅使用Python读取,写入和解析JSON。

json ·dumps()

json.dumps()函数将Python对象转换为json字符串。



用法:
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)

参数:
obj:将obj序列化为JSON格式的流
skipkeys:如果skipkeys为true(默认值:False),则将跳过不是基本类型(str,int,float,bool,None)的dict键,而不是引发TypeError。
ensure_ascii:如果ensure_ascii为true(默认值),则确保输出中所有传入的非ASCII字符都已转义。如果ensure_ascii为false,则将输出这些字符as-is。
check_circular:如果check_circular为false(默认值:True),则将跳过对容器类型的循环引用检查,并且循环引用将导致OverflowError(或更糟)。
allow_nan:如果allow_nan为false(默认值:True),则严格符合JSON规范的序列化超出范围的浮点值(nan,inf,-inf)将是ValueError。如果allow_nan为true,则将使用它们的JavaScript等效项(NaN,Infinity和-Infinity)。
indent:如果缩进是非负整数或字符串,则JSON数组元素和对象成员将是具有该缩进级别的pretty-printed。缩进级别0,负数或“”只会插入换行符。无(默认)选择最紧凑的表示形式。使用正整数缩进会使每个级别缩进多个空格。如果缩进是字符串(例如“\t”),则该字符串用于缩进每个级别。
separators:如果指定,分隔符应为(item_separator,key_separator)元组。如果缩进为“无”,则默认值为(‘,’,‘:’),否则为(‘,’,‘:’)。为了获得最紧凑的JSON表示形式,您应该指定(',',':')以消除空格。
default:如果指定了默认值,则默认值应该是一个调用本来无法序列化的对象的函数。它应该返回该对象的JSON可编码版本或引发TypeError。如果未指定,则引发TypeError。
sort_keys:如果sort_keys为true(默认值:False),则字典的输出将按键排序。

范例1:将Python字典传递给json.dumps()函数将返回一个字符串。

import json 
  
# Creating a dictionary 
Dictionary ={1:'Welcome', 2:'to', 
            3:'Geeks', 4:'for', 
            5:'Geeks'} 
   
# Converts input dictionary into 
# string and stores it in json_string 
json_string = json.dumps(Dictionary) 
print('Equivalent json string of input dictionary:', 
      json_string) 
print("        ") 
  
# Checking type of object 
# returned by json.dumps 
print(type(json_string))

输出

Equivalent json string of dictionary:{“1”:“Welcome”, “2”:“to”, “3”:“Geeks”, “4”:“for”, “5”:“Geeks”}
<class ‘str’>

范例2:通过将跳过键设置为True(默认值:False),我们将自动跳过不是基本类型的键。

import json 
  
  
Dictionary ={(1, 2, 3):'Welcome', 2:'to', 
            3:'Geeks', 4:'for', 
            5:'Geeks'} 
  
  
# Our dictionary contains tuple 
# as key, so it is automatically  
# skipped If we have not set 
# skipkeys = True then the code  
# throws the error  
json_string = json.dumps(Dictionary,  
                         skipkeys = True) 
  
print('Equivalent json string of dictionary:',  
      json_string)

输出

Equivalent json string of dictionary:{“2”:“to”, “3”:“Geeks”, “4”:“for”, “5”:“Geeks”}

范例3:

import json 
  
  
# We are adding nan values 
# (out of range float values) 
# in dictionary 
Dictionary ={(1, 2, 3):'Welcome', 2:'to', 
            3:'Geeks', 4:'for', 
            5:'Geeks', 6:float('nan')} 
  
# If we hadn't set allow_nan to  
# true we would have got  
# ValueError:Out of range float  
# values are not JSON compliant 
json_string = json.dumps(Dictionary, 
                         skipkeys = True, 
                         allow_nan = True) 
  
print('Equivalent json string of dictionary:',  
      json_string)

输出:



Equivalent json string of dictionary:{“2”:“to”, “3”:“Geeks”, “4”:“for”, “5”:“Geeks”, “6”:NaN}

范例4:

import json 
  
  
Dictionary ={(1, 2, 3):'Welcome', 2:'to', 
            3:'Geeks', 4:'for', 
            5:'Geeks', 6:float('nan')} 
  
# Indentation can be used  
# for pretty-printing 
json_string = json.dumps(Dictionary,  
                         skipkeys = True,  
                         allow_nan = True, 
                         indent = 6) 
  
print('Equivalent json string of dictionary:',  
      json_string)

输出:

Equivalent json string of dictionary:{
      "2":"to",
      "3":"Geeks",
      "4":"for",
      "5":"Geeks",
      "6":NaN
}

范例5:

import json 
  
Dictionary ={(1, 2, 3):'Welcome', 2:'to', 
            3:'Geeks', 4:'for', 
            5:'Geeks', 6:float('nan')} 
  
# If specified, separators should be 
# an (item_separator, key_separator)tuple 
# Items are seperated by '.' and key, 
# values are seperated by '=' 
json_string = json.dumps(Dictionary, 
                         skipkeys = True,  
                         allow_nan = True, 
                         indent = 6, 
                         separators =(". ", " = ")) 
  
print('Equivalent json string of dictionary:', 
      json_string)

输出:

Equivalent json string of dictionary:{
      "2" = "to". 
      "3" = "Geeks". 
      "4" = "for". 
      "5" = "Geeks". 
      "6" = NaN
}

范例#6:

import json 
  
Dictionary ={'c':'Welcome', 'b':'to', 
            'a':'Geeks'} 
  
json_string = json.dumps(Dictionary, 
                         indent = 6, 
                         separators =(". ", " = "), 
                         sort_keys = True) 
  
print('Equivalent json string of dictionary:', 
      json_string)

输出:

Equivalent json string of dictionary:{
      "a" = "Geeks". 
      "b" = "to". 
      "c" = "Welcome"
}



相关用法


注:本文由纯净天空筛选整理自sathvik chiramana大神的英文原创作品 json.dumps() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。