python2.7入門---JSON

    此次咱們來看如何使用 Python 語言來編碼和解碼 JSON 對象。首先,咱們得了解,JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,易於人閱讀和編寫。而後呢,使用 JSON 函數須要導入 json 庫:import jsonhtml

 

函數 描述
json.dumps 將 Python 對象編碼成 JSON 字符串
json.loads 將已編碼的 JSON 字符串解碼爲 Python 對象

    json.dumps 用於將 Python 對象編碼成 JSON 字符串。看下語法:python

 

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

    如下爲實例:git

 

#!/usr/bin/python import json data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = json.dumps(data) print json

    以上代碼執行結果爲:github

 

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]

    使用參數讓 JSON 數據格式化輸出:json

 

>>> import json >>> print json.dumps({'a': 'luyaran', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': ')) { "a": "luyaran", "b": 7 }

    咱們來看python 原始類型向 json 類型的轉化對照表:數組

 

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

    json.loads 用於解碼 JSON 數據。該函數返回 Python 字段的數據類型。看下語法:函數

 

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

    如下實例展現了Python 如何解碼 JSON 對象:編碼

 

#!/usr/bin/python import json jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = json.loads(jsonData) print text

    以上代碼執行結果爲:spa

 

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

    來看下json 類型轉換到 python 的類型對照表:.net

 

JSON Python
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

    想看更多內容參考:https://docs.python.org/2/library/json.html。而後咱們來看第三方庫。Demjson 是 python 的第三方模塊庫,可用於編碼和解碼 JSON 數據,包含了 JSONLint 的格式化及校驗功能。Github 地址:https://github.com/dmeranda/demjson。官方地址:http://deron.meranda.us/python/demjson/。在使用 Demjson 編碼或解碼 JSON 數據前,咱們須要先安裝 Demjson 模塊:

 

$ tar -xvzf demjson-2.2.3.tar.gz $ cd demjson-2.2.3 $ python setup.py install

    更多安裝介紹查看:http://deron.meranda.us/python/demjson/install

    看下json函數表單:

 

函數 描述
encode 將 Python 對象編碼成 JSON 字符串
decode 將已編碼的 JSON 字符串解碼爲 Python 對象

    Python encode() 函數用於將 Python 對象編碼成 JSON 字符串。看下語法:

 

demjson.encode(self, obj, nest_level=0)

    如下實例將數組編碼爲 JSON 格式數據:

 

#!/usr/bin/python import demjson data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = demjson.encode(data) print json

    以上代碼執行結果爲:

 

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

    Python 能夠使用 demjson.decode() 函數解碼 JSON 數據。該函數返回 Python 字段的數據類型。看下語法:

 

demjson.decode(self, txt)

    如下實例展現了Python 如何解碼 JSON 對象:

 

#!/usr/bin/python import demjson json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = demjson.decode(json) print text

    以上代碼執行結果爲:

 

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

    好啦,由於這部分比較簡單,因此就不作過多的贅述了。若是感受不錯的話,請多多點贊支持哦。。。

  原文連接:https://blog.csdn.net/luyaran/article/details/80005582

相關文章
相關標籤/搜索