Chinaunix首页 | 论坛 | 博客
  • 博客访问: 855352
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-09-27 13:44:40

from:http://bkeep.blog.163.com/blog/static/12341429020113156582685/

一、JSON的格式:

1,对象:

{name:"Peggy",email:"peggy@gmail.com",homepage:""}

属性 :  , 属性 :  , 属性 :  }

 

2,数组是有顺序的值的集合。一个数组开始于"[",结束于"]",值之间用","分隔。

[

{name:"Peggy",email:"peggy@gmail.com",homepage:""}, {name:"Peggy",email:"peggy@gmail.com",homepage:""},

{name:"Peggy",email:"peggy@gmail.com",homepage:""}

]

3, 值可以是字符串、数字、truefalsenull,也可以是对象或数组。这些结构都能嵌套。

 

4,json示例:

import json

# Converting Python to JSON

json_object = json.write( python_object )

 #注:read/write是json-py.py和minijson.py的方法,而python2.6开始自带的lib库里用的是simplejson.py,其没有read/write方法,而是load/loads/dump/dumps

# Converting JSON to Python

python_object = json.read( json_object )

 

5,simplejson 示例:

import simplejson

# Converting Python to JSON

json_object = simplejson.dumps( python_object )

# Converting JSON to Python

python_object = simplejson.loads( json_object )

 

二、pythonweb接口上查询信息

1,先看个例子

>>> import urllib

>>> url=''

>>> page=urllib.urlopen(url)

>>> data=page.read()

>>> print data           //这个就是json的数据结构,str类型

{"total":1,"data":[{"outGuaranteeTime":"","assetsNum":"B50070100007003","cabinet":"H05","deviceModel":"PowerEdge 1950","hostname":"hzshterm1.alibaba.com","logicSite":"中文站","memoryInfo":{"amount":4,"size":8192},"ip":"172.16.20.163","isOnline":true,"useState":"使用中","serviceTag":"729HH2X","cpuInfo":{"amount":2,"masterFrequency":1995,"model":"Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz","coreNum":8,"l2CacheSize":6144},"cabinetPositionNum":"","buyTime":"2009-06-29","manageIp":"172.31.58.223","idc":"杭州德胜机房","responsibilityPerson":"张之诚"}],"errorMsg":"","isSuccess":true}

>>> type(data)

 

2,有了json数据结构,我却不知道怎么把它解析出来,幸亏有了李建辉的指导。大概思路是:

首先,json基本上是key/value的,python中就叫字典。既然是字典,那就应该安照读字典的方式去读。

将上面的data转为字典类型,这里用json模块的read方法。

 

>>> import json

>>> ddata=json.read(data)

>>> ddata

{'isSuccess': True, 'errorMsg': '', 'total': 1, 'data': [{'isOnline': True, 'idc': '\xe6\x9d\xad\xe5\xb7\x9e\xe5\xbe\xb7\xe8\x83\x9c\xe6\x9c\xba\xe6\x88\xbf', 'assetsNum': 'B50070100007003', 'responsibilityPerson': '\xe5\xbc\xa0\xe4\xb9\x8b\xe8\xaf\x9a', 'deviceModel': 'PowerEdge 1950', 'serviceTag': '729HH2X', 'ip': '172.16.20.163', 'hostname': 'hzshterm1.alibaba.com', 'manageIp': '172.31.58.223', 'cabinet': 'H05', 'buyTime': '2009-06-29', 'useState': '\xe4\xbd\xbf\xe7\x94\xa8\xe4\xb8\xad', 'memoryInfo': {'amount': 4, 'size': 8192}, 'cpuInfo': {'coreNum': 8, 'l2CacheSize': 6144, 'amount': 2, 'model': 'Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz', 'masterFrequency': 1995}, 'cabinetPositionNum': '', 'outGuaranteeTime': '', 'logicSite': '\xe4\xb8\xad\xe6\x96\x87\xe7\xab\x99'}]}

>>> 

看看ddata已经是dict类型了

>>> type(ddata)

 

其次,我们以读字典中key”data”对应的键值

>>> ddata['data']    //查看字典的方法!

[{'isOnline': True, 'idc': '\xe6\x9d\xad\xe5\xb7\x9e\xe5\xbe\xb7\xe8\x83\x9c\xe6\x9c\xba\xe6\x88\xbf', 'assetsNum': 'B50070100007003', 'responsibilityPerson': '\xe5\xbc\xa0\xe4\xb9\x8b\xe8\xaf\x9a', 'deviceModel': 'PowerEdge 1950', 'serviceTag': '729HH2X', 'ip': '172.16.20.163', 'hostname': 'hzshterm1.alibaba.com', 'manageIp': '172.31.58.223', 'cabinet': 'H05', 'buyTime': '2009-06-29', 'useState': '\xe4\xbd\xbf\xe7\x94\xa8\xe4\xb8\xad', 'memoryInfo': {'amount': 4, 'size': 8192}, 'cpuInfo': {'coreNum': 8, 'l2CacheSize': 6144, 'amount': 2, 'model': 'Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz', 'masterFrequency': 1995}, 'cabinetPositionNum': '', 'outGuaranteeTime': '', 'logicSite': '\xe4\xb8\xad\xe6\x96\x87\xe7\xab\x99'}]

 

>>>type(ddata[‘data’])

 

发现ddata[‘data’]是一个列表,列表就要用序号来查询

>>> ddata['data'][0]         //查看列表的方法!

{'isOnline': True, 'idc': '\xe6\x9d\xad\xe5\xb7\x9e\xe5\xbe\xb7\xe8\x83\x9c\xe6\x9c\xba\xe6\x88\xbf', 'assetsNum': 'B50070100007003', 'responsibilityPerson': '\xe5\xbc\xa0\xe4\xb9\x8b\xe8\xaf\x9a', 'deviceModel': 'PowerEdge 1950', 'serviceTag': '729HH2X', 'ip': '172.16.20.163', 'hostname': 'hzshterm1.alibaba.com', 'manageIp': '172.31.58.223', 'cabinet': 'H05', 'buyTime': '2009-06-29', 'useState': '\xe4\xbd\xbf\xe7\x94\xa8\xe4\xb8\xad', 'memoryInfo': {'amount': 4, 'size': 8192}, 'cpuInfo': {'coreNum': 8, 'l2CacheSize': 6144, 'amount': 2, 'model': 'Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz', 'masterFrequency': 1995}, 'cabinetPositionNum': '', 'outGuaranteeTime': '', 'logicSite': '\xe4\xb8\xad\xe6\x96\x87\xe7\xab\x99'}

>>> 

 

呵呵,ddata[‘data’]列表的0号元素是个字典。。

好,那我们查查keyidc的键值是多少

>>> ddata['data'][0]['idc']          //查看字典的方法!

'\xe6\x9d\xad\xe5\xb7\x9e\xe5\xbe\xb7\xe8\x83\x9c\xe6\x9c\xba\xe6\x88\xbf'

>>> print ddata['data'][0]['idc']   //呵呵,为什么print搞出来的是汉字呢?

杭州德胜机房

 

看到这里终于明白怎么解析json数据结构了。。。

那就是一层一层往下剥

-------------------------------------------------------------------------------

#! /usr/bin/env python
#coding=utf-8
import json

s = '[{"name":"鸟巢","point":{"lat":"39.990","lng":"116.397"},"desc":"奥运会主场 地"},{"name":"北大乒乓球馆","point":{"lat":"39.988","lng":"116.315"},"desc":"乒乓 球比赛场地"},{"name":"北京工人体育场","point": {"lat":"39.930","lng":"116.446"},"desc":"足球比赛场地"}]'

locations = json.read(s)

 #注:read是json-py.py和minijson.py的方法,而python2.6开始自带的lib库里用的是simplejson.py,其没有read方法,而是load/loads
print str(len(locations))
for location in locations:
    print location["name"]
    print location["point"]["lat"]

-------------------------------------------------------------------------------

 #!/usr/local/bin/python

#coding = utf-8

import os

import json Res='[{"brief":"ooooo","class_extid":13,"create_time":1131783174,"face_id":4,"flag":6777217,"flag_ext":0,"level":0,"max_member":100,"memo":"m~F~M0m~Zm~@~B","name":"10502","option":2,"ul":[{"flag":4,"u":285},{"flag":4,"u":35}]}]'

qDic = json.loads(Res)

for i in qDic:

   print i["class_extid"

       for j in i["ul"]:

            print str(j["flag"]) + "===" + str(j["u"])

=================================================================================

root@gs_develop_154_62:~/decli_script/script# python t4.sh
13
4===285
4===35
root@gs_develop_154_62:~/decli_script/script#

PS:更多范例请参考

阅读(56149) | 评论(2) | 转发(2) |
给主人留下些什么吧!~~

凤城骄子2015-02-05 17:52:41

大概都读懂了,我现在的需求是如何修改字典中指定key的值呢?

xiaoyue19922014-05-19 22:23:32

好感谢你啊~~我终于弄懂了!!谢谢!