xiaowenhui

Python—JSON数据解析

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}]
{u\'Enemy Behind\': {u\'rating\': u\'PG\', u\'description\': u\'Talk about a US-Japan war\', u\'format\': u\'DVD\', u\'stars\': u\'10\', u\'year\': u\'2003\', u\'type\': u\'War, Thriller\'}, u\'Ishtar\': {u\'rating\': u\'PG\', u\'type\': u\'Comedy\', u\'description\': u\'Viewable boredom\', u\'stars\': u\'2\', u\'format\': u\'VHS\'}, u\'Transformers\': {u\'rating\': u\'R\', u\'description\': u\'A schientific fiction\', u\'format\': u\'DVD\', u\'stars\': u\'8\', u\'year\': u\'1989\', u\'type\': u\'Anime, Science Fiction\'}, u\'Trigun\': {u\'rating\': u\'PG\', u\'description\': u\'Vash the Stampede!\', u\'format\': u\'DVD\', u\'episodes\': u\'4\', u\'stars\': u\'10\', u\'type\': u\'Anime, Action\'}}

 

分类:

技术点:

相关文章:

  • 2021-09-29
  • 2021-09-19
  • 2021-10-04
  • 2021-11-17
  • 2022-12-23
  • 2021-11-17
  • 2021-11-17
猜你喜欢
  • 2021-09-29
  • 2021-09-09
  • 2021-09-29
  • 2021-09-14
  • 2021-09-29
  • 2022-12-23
  • 2021-09-29
相关资源
相似解决方案