python中将字典转换成其json字符串,pythonjson
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"}'
json本身就是字符串,是符合json格式的字符串。
所以,你说的,字符串转json,就是不正确的描述。
一般正常的用法是:
涉及到,在json字符串,来自字符变量或文件内容,和不同类型的变量,之间的转换。
变量转json:
json.dumps或json.dump
json转变量:
json.loads或json.load
详解:
【整理】Python中将(字典,列表等)变量格式化成(漂亮的,树形的,带缩进的,JSON方式的)字符串输出
【整理】什么是JSON+如何处理JSON字符串
(此处不给贴地址,请自己用google搜标题,即可找到帖子地址)
json数据本身就是一段文本(字符串),比如'{"id": 5}'
python的语法基本上是json的超集。读取简单,代码
import json
a=json.loads('{ "id":5}') #把'{ "id":5}'读到变量a中
相关内容
- Python的垃圾回收机制深入分析,python垃圾回收
- Python的内存泄漏及gc模块的使用分析,python泄漏gc模块
- python的迭代器与生成器实例详解,python生成器
- Python下singleton模式的实现方法,pythonsingleton
- python采集博客中上传的QQ截图文件,
- python中使用百度音乐搜索的api下载指定歌曲的lrc歌词,
- python使用pyhook监控键盘并实现切换歌曲的功能,python
- python中使用pyhook实现键盘监控的例子,pythonpyhook
- Python中使用PyHook监听鼠标和键盘事件实例,pythonpyhook
- Python中使用 Selenium 实现网页截图实例,pythonselenium
评论关闭