Python操作json的方法实例分析

yipeiwu_com7年前Python基础

本文实例讲述了Python操作json的方法。分享给大家供大家参考,具体如下:

python中对json操作方法有两种,解码loads()和编码dumps()

简单来说:

import json
dicts = json.loads()   #loads()方法,将json串解码为python对象,字典
json = json.dumps(dicts) #dumps()方法,将python字典编码为json串

简单例子:

>>> import json
>>> dicts = {'name':'test','type':[{'happy':'fish'},{'sad':'man'}]}  #python的字典
>>> print(dicts.keys())        #python的字典可以通过内置的字典方法操作keys 和values
dict_keys(['type', 'name'])
>>> print(dicts['name'])
test
>>> print(dicts['type'][0]['happy'])
fish
>>> print(dicts['type'][1]['sad'])
man
>>> j = json.dumps(dicts)      #通过dumps()方法,将python字典编码为json串
>>> j
'{"type": [{"happy": "fish"}, {"sad": "man"}], "name": "test"}'
>>> print(j['name'])         #json不能通过字典方法获取keys 和 values了。
Traceback (most recent call last):
 File "<pyshell#10>", line 1, in <module>
  print(j['name'])
TypeError: string indices must be integers

更多的信息,可以参考python内部的json文档:

python>>> help(json)

如下图所示:

或者官方文档:
http://docs.python.org/library/json.html

PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans

更多Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python通过递归遍历出集合中所有元素的方法

本文实例讲述了Python通过递归遍历出集合中所有元素的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:'''''通过递归遍历出集合中的所有元素 Created o...

python实现监控linux性能及进程消耗性能的方法

本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下: # -*- coding: utf-8 -*- """ Created on Tue J...

粗略分析Python中的内存泄漏

引子 之前一直盲目的认为 Python 不会存在内存泄露, 但是眼看着上线的项目随着运行时间的增长 而越来越大的内存占用, 我意识到我写的程序在发生内存泄露, 之前 debug 过 lo...

Python实现代码统计工具

本文实例为大家分享了Python实现代码统计工具的具体代码,供大家参考,具体内容如下 思路:首先获取所有文件,然后统计每个文件中代码的行数,最后将行数相加. 实现的功能: 统计每个文件的...

python的staticmethod与classmethod实现实例代码

本文源于一时好奇,想要弄清出python的staticmethod()这一builtin方法的实现,查了一些资料(主要是python官方手册了)汇集于此 python在类中,有三种调用m...