码迷,mamicode.com
首页 > 编程语言 > 详细

Python—JSON数据解析

时间:2015-09-14 19:16:30      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

1.安装pip

pip是python的包管理工具,使用它能非常方便地安装和卸载各种python工具包

第一步:直接用浏览器访问地址:https://raw.github.com/pypa/pip/master/contrib/get-pip.py,直接打开了get-pip.py的源代码,可以直接把内容拷贝出来,然后在本地创建get-pip.py

第二步:控制台进入到get-pip.py所在目录,运行代码:

python get-pip.py

pip默认安装实在当前版本python目录的script下,所以将此目录设置到环境变量path中即可,我的目录是 C:\Python27\Scripts

2.安装demjson模块

 windows下,打开cmd控制台窗口,使用pip命令安装,命令如下:

pip install demjson

 

3.json字符串和python对象之间转换的示例代码如下

# -*- coding:UTF-8 -*-
‘‘‘
Created on 2015年9月14日

@author: xiaowenhui
‘‘‘

import demjson

‘‘‘
encode:编码,将python对象编码成JSON字符串
decode:解码,将JSON字符串解码成python对象
‘‘‘

data1 = [ { ‘a‘ : 1, ‘b‘ : 2, ‘c‘ : 3, ‘d‘ : 4, ‘e‘ : 5 } ]
json1 = demjson.encode(data1)
print json1

json2 = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘
data2 = demjson.decode(json2)
print data

json3 = "{‘Transformers‘: {‘rating‘: ‘R‘, ‘description‘: ‘A schientific fiction‘, ‘format‘: ‘DVD‘, ‘stars‘: ‘8‘, ‘year‘: ‘1989‘, ‘type‘: ‘Anime, Science Fiction‘}, ‘Ishtar‘: {‘rating‘: ‘PG‘, ‘type‘: ‘Comedy‘, ‘description‘: ‘Viewable boredom‘, ‘stars‘: ‘2‘, ‘format‘: ‘VHS‘}, ‘Enemy Behind‘: {‘rating‘: ‘PG‘, ‘description‘: ‘Talk about a US-Japan war‘, ‘format‘: ‘DVD‘, ‘stars‘: ‘10‘, ‘year‘: ‘2003‘, ‘type‘: ‘War, Thriller‘}, ‘Trigun‘: {‘rating‘: ‘PG‘, ‘description‘: ‘Vash the Stampede!‘, ‘format‘: ‘DVD‘, ‘episodes‘: ‘4‘, ‘stars‘: ‘10‘, ‘type‘: ‘Anime, Action‘}}"
data3 = demjson.decode(json3)
print data3

 

输出结果如下:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]
[{a: 1, c: 3, b: 2, e: 5, d: 4}]
{uEnemy Behind: {urating: uPG, udescription: uTalk about a US-Japan war, uformat: uDVD, ustars: u10, uyear: u2003, utype: uWar, Thriller}, uIshtar: {urating: uPG, utype: uComedy, udescription: uViewable boredom, ustars: u2, uformat: uVHS}, uTransformers: {urating: uR, udescription: uA schientific fiction, uformat: uDVD, ustars: u8, uyear: u1989, utype: uAnime, Science Fiction}, uTrigun: {urating: uPG, udescription: uVash the Stampede!, uformat: uDVD, uepisodes: u4, ustars: u10, utype: uAnime, Action}}

 

Python—JSON数据解析

标签:

原文地址:http://www.cnblogs.com/xiaowenhui/p/4807888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!