python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

yipeiwu_com6年前Python基础

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

Python3 JSON 数据解析

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。

Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

  • json.dumps(): 对数据进行编码。
  • json.loads(): 对数据进行解码。

在写网络爬虫的时候,有时候会抓取到一些json格式的字符串,想要通过python字典的方式对字串中的内容进行寻址,则需要将json字符串先转换为python字典。

dumps()函数:

loads()函数:

示例:

import json
class forDatas:
 def __init__(self):
  pass
 def testJson(self):
  # 定义一个字典
  d = {'a': 1,
    'b': 2,
    'c': 'asdf'}
  print('d:', d, type(d))
  # dict to str
  d1 = json.dumps(d)
  print('d1:', d1, type(d1))
  # str to dict
  d2 = json.loads(d1)
  print('d2:', d2, type(d2))
if __name__ == '__main__':
 tt = forDatas()
 tt.testJson()

总结

以上所述是小编给大家介绍的python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

使用虚拟环境打包python为exe 文件的方法

使用过anaconda环境下打包py文件的一点感悟,使用的是pyinstaller+anaconda环境下打包py文件 打包: pyinstaller -F -w -i logo.ico...

Python中if elif else及缩进的使用简述

代码如下所示: scole = input("input your scole:") if scole>90: print("A") elif scole>80:...

Python math库 ln(x)运算的实现及原理

Python math库 ln(x)运算的实现及原理

这个是很有用的一个运算,除了本身可以求自然对数,还是求指数函数需要用到的基础函数。 实现原理就是泰勒展开,最简单是在x=1处进行泰勒展开: 但该函数离1越远越难收敛,同时大于2时无法收...

python统计中文字符数量的两种方法

方法一: def str_count(str): '''找出字符串中的中英文、空格、数字、标点符号个数''' count_en = count_dg = count_sp = c...

python实现读取大文件并逐行写入另外一个文件

<pre name="code" class="python">creazy.txt文件有4G,逐行读取其内容并写入monday.txt文件里。 def crea...