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”}

范例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"

}

python json dumps 自定义_Python json.dumps()用法及代码示例相关推荐

  1. python的datetime举例_Python datetime.timedelta()用法及代码示例

    Python timedelta()函数存在于datetime库中,该函数通常用于计算日期差,也可以用于Python中的日期操作.这是执行日期操作的最简单方法之一. 用法: datetime.time ...

  2. python的mag模块_Python Decimal max_mag()用法及代码示例

    Decimal#max_mag():max_mag()是一个Decimal类方法,该方法比较两个Decimal值并返回两个最大值(忽略它们的符号). 用法: Decimal.max_mag() 参数: ...

  3. python的mag模块_Python Decimal min_mag()用法及代码示例

    Decimal#min_mag():min_mag()是一个Decimal类方法,它比较两个Decimal值并返回两个最小值,而忽略它们的符号. 用法: Decimal.min_mag() 参数: D ...

  4. python not is函数_Python unittest assertIsNotNone()用法及代码示例

    assertIsNotNonePython中的()是单元测试库函数,用于单元测试中以检查输入值是否为None.此函数将使用两个参数作为输入,并根据断言条件返回布尔值.如果输入值不等于无assertIs ...

  5. python中squeeze函数_Python numpy.squeeze()用法及代码示例

    当我们要从数组形状中删除一维条目时,将使用numpy.squeeze()函数. 用法: numpy.squeeze(arr, axis=None ) 参数: arr :[数组]输入数组. axis : ...

  6. python中argmin函数_Python numpy.argmin()用法及代码示例

    numpy.argmin(array,axis = None,out = None):返回特定轴上数组min元素的索引. 参数: array:Input array to work on axis : ...

  7. python json dumps 自定义_Python json.dumps 自定义序列化操作

    def login_ajax(request): if request.method == "GET": return render(request, 'login_ajax.ht ...

  8. html里fill怎么自定义,HTML canvas fill()用法及代码示例

    画布fill()方法用于填充当前绘图路径.画布fill()方法的默认颜色是黑色. 用法: context.fill() 示例1: HTML canvas fillRect() Method width ...

  9. python实现关联算法_python实现关联规则算法Apriori代码示例

    本篇文章小编给大家分享一下python实现关联规则算法Apriori代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 首先导入包含apriori ...

最新文章

  1. centos+ffmpeg安装配置+切片
  2. python语言怎么用-Python语言应用解析,如何入门学Python?
  3. python中用lxml解析html
  4. fastjson将json字符串转为Map对象,拿走不谢
  5. 解决 Eclipse 项目有红感叹号的方法
  6. zemax操作数_ZEMAX与像差理论:二级光谱的ZEMAX描述与详解
  7. OpenCASCADE:Modeling Data之二维几何
  8. 【python数据挖掘课程】二十一.朴素贝叶斯分类器详解及中文文本舆情分析
  9. lpc2000 filash utility 程序烧写工具_单片机烧录程序的次数
  10. 【Sikuli】Sikuli 文档
  11. jq之toggle()
  12. 颉伟/郭勇/李伟合作阐释哺乳动物早期胚胎发育中表观重编程和基因印记的进化保守性和物种特异性...
  13. KARL MAYER卡尔迈耶驱动器维修SP0405-KM SP0404 SP0403
  14. 数字信号处理:时域采样定理与频域采样定理
  15. Question | 怎样有效杜绝“羊毛党“的薅羊毛行为?
  16. 潘悟云方言计算机,山东方言精组与见晓组声母的分合研究
  17. 自我营销(转帖自 TI E2E 工程师社区 (Beta))
  18. javascript atob()函数和 btoa()函数-Base64的编码与解码
  19. 面对来势汹汹的AI大潮,你该如何应对?
  20. Unity 打包APK 适配全面屏、刘海屏、水滴屏、挖孔屏

热门文章

  1. delphi idtcpclient和idtcpserver的心跳包
  2. ORACLE行转列通用过程(转)
  3. Invalid byte 2 of 2-byte UTF-8 sequence解决方案
  4. 解决输入框自动填充账号密码的问题
  5. 【图解+全文】工信部关于印发“十四五”大数据产业发展规划的通知
  6. 【报告分享】2021抖音电商生态发展报告.pdf(附下载链接)
  7. gcc编译ceres-solver报错‘is_trivially_default_constructible’ is not a member of ‘std’
  8. png文件合并_程序员学习之在Python中使用PDF:阅读、旋转、合并和拆分
  9. 你的ERP系统选对了吗?
  10. 轨迹压缩文献阅读 TrajStore: An Adaptive Storage System for Very Large Trajectory Data Sets