python操做json技巧

每次遇到json loads/dumps始終搞不清方向,寫段代碼試下:html

 

[python] view plain copypython

  1. import json  
  2.   
  3. dict_ = {1:2, 3:4, "55":"66"}  
  4.   
  5. # test json.dumps  
  6.   
  7. print type(dict_), dict_  
  8. json_str = json.dumps(dict_)  
  9. print "json.dumps(dict) return:"  
  10. print type(json_str), json_str  
  11.   
  12. # test json.loads  
  13. print "\njson.loads(str) return"  
  14. dict_2 = json.loads(json_str)  
  15. print type(dict_2), dict_2  

 

 

程序結果:web

<type 'dict'> {'55': '66', 1: 2, 3: 4}
json.dump(dict) return:
<type 'str'> {"55": "66", "1": 2, "3": 4}


json.loads(str) return
<type 'dict'> {u'55': u'66', u'1': 2, u'3': 4}json

 

總結:api

json.dumps : dict轉成str數組

json.loads:str轉成dict數據結構

如此簡單。app

 

python操做json技巧總結ui

http://www.jb51.net/Special/800.htmurl

Python解析json數據結構範例 

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

1、JSON的格式:

1,對象:

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

{ 屬性 : 值 , 屬性 : 值 , 屬性 : 值 }

 

2,數組是有順序的值的集合。一個數組開始於"[",結束於"]",值之間用","分隔。

[

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

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

]

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 )

 

2、pythonweb接口上查詢信息

1,先看個例子

>>> import urllib

>>> url='http://a.bkeep.com/page/api/saInterface/searchServerInfo.htm?serviceTag=729HH2X'

>>> 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號元素是個字典。。

好,那咱們查查key爲idc的鍵值是多少

>>> 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:更多範例請參考

http://docs.python.org/library/json.html

相關文章
相關標籤/搜索