【轉載】python json

概念

序列化(Serialization):將對象的狀態信息轉換爲可以存儲或可以通過網絡傳輸的過程,傳輸的格式可以是JSON、XML等。反序列化就是從存儲區域(JSON,XML)讀取反序列化對象的狀態,重新創建該對象。

JSON(JavaScript Object Notation):一種輕量級數據交換格式,相對於XML而言更簡單,也易於閱讀和編寫,機器也方便解析和生成,Json是JavaScript中的一個子集。

Python2.6開始加入了JSON模塊,無需另外下載,Python的Json模塊序列化與反序列化的過程分別是 encoding和 decoding

encoding:把一個Python對象編碼轉換成Json字符串
decoding:把Json格式字符串解碼轉換成Python對象
對於簡單數據類型(string、unicode、int、float、list、tuple、dict),可以直接處理。

json.*dumps方法對簡單數據類型encoding:*

import json
data = [{'a':"A",'b':(2,4),'c':3.0}]  #list對象
print "DATA:",repr(data)

data_string = json.dumps(data)
print "JSON:",data_string

輸出:

DATA: [{'a':'A','c':3.0,'b':(2,4)}] #python的dict類型的數據是沒有順序存儲的
JSON: [{"a":"A","c":3.0,"b":[2,4]}]  

json.*loads方法處理簡單數據類型的decoding(解碼)轉換*

import json
data = [{'a':"A",'b':(2,4),'c':3.0}]  #list對象

data_string = json.dumps(data)
print "ENCODED:",data_string

decoded = json.loads(data_string)
print "DECODED:",decoded

print "ORIGINAL:",type(data[0]['b'])
print "DECODED:",type(decoded[0]['b'])

輸出:

ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}]
DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]
ORIGINAL: <type 'tuple'>
DECODED: <type 'list'>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章