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


#这是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

json本身就是字符串,是符合json格式的字符串。
所以,你说的,字符串转json,就是不正确的描述。

一般正常的用法是:
涉及到,在json字符串,来自字符变量或文件内容,和不同类型的变量,之间的转换。

变量转json:
json.dumps或json.dump

json转变量:
json.loads或json.load

详解:
【整理】Python中将(字典,列表等)变量格式化成(漂亮的,树形的,带缩进的,JSON方式的)字符串输出
【整理】什么是JSON+如何处理JSON字符串

(此处不给贴地址,请自己用google搜标题,即可找到帖子地址)
 

python中,怎把json对象转成字符串

json数据本身就是一段文本(字符串),比如'{"id": 5}'
python的语法基本上是json的超集。读取简单,代码
import json
a=json.loads('{ "id":5}') #把'{ "id":5}'读到变量a中
 

评论关闭