python中将字典转换成其json字符串

yipeiwu_com5年前Python基础

#这是Python中的一个字典

dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } 

//这是javascript中的一个JSON对象

json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串(不能传递所以需要将其转换成字符串先),Python有一个叫simplejson的库可以方便的完成JSON的生成和解析,这个包已经包含在Python2.6中,就叫json 主要包含四个方法: dump和dumps(从Python生成JSON),load和loads(解析JSON成Python的数据类型)dump和dumps的唯一区别是dump会生成一个类文件对象,dumps会生成字符串,同理load和loads分别解析类文件对象和字符串格式的JSON

import json dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } json.dumps(dic) #output: #'{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}'

相关文章

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

python常见数制转换实例分析

本文实例讲述了python常见数制转换用法。分享给大家供大家参考。具体分析如下: 1.进位制度 Python中二进制是以0b开头的: 例如: 0b11 则表示十进制的3 8进制是以0开头...

Python操作MySQL数据库实例详解【安装、连接、增删改查等】

本文实例讲述了Python操作MySQL数据库。分享给大家供大家参考,具体如下: 1、安装 通过Python连接MySQL数据库有很多库,这里使用官方推荐的MySQL Connector...

python3个性签名设计实现代码

python3个性签名设计实现代码

本文实例为大家分享了python个性签名设计的具体代码,供大家参考,具体内容如下 参考博客:Python GUI Tkinter简单实现个性签名设计 参考博客:python3爬虫之设计签...

Python中%r和%s的详解及区别

Python中%r和%s的详解 %r用rper()方法处理对象 %s用str()方法处理对象 有些情况下,两者处理的结果是一样的,比如说处理int型对象。 例一: print...