手机
当前位置:查字典教程网 >脚本专栏 >python >python中将字典转换成其json字符串
python中将字典转换成其json字符串
摘要:#这是Python中的一个字典dic={'str':'thisisastring','list':[1,2,'a','b'],'sub_di...

#这是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中将字典转换成其json字符串】相关文章:

python分割和拼接字符串

python三元运算符实现方法

Python Trie树实现字典排序

Python 字符串定义

python 字符串格式化代码

python 将字符串转换成字典dict

python3图片转换二进制存入mysql

python解析json实例方法

python创建和使用字典实例详解

python教程之用py2exe将PY文件转成EXE文件

精品推荐
分类导航