Python-讀入json檔案並進行解析及json基本操作,python-json

來源:互聯網
上載者:User

Python-讀入json檔案並進行解析及json基本操作,python-json

import jsondef resolveJson(path):    file = open(path, "rb")    fileJson = json.load(file)    field = fileJson["field"]    futures = fileJson["futures"]    type = fileJson["type"]    name = fileJson["name"]    time = fileJson["time"]    return (field, futures, type, name, time)def output():    result = resolveJson(path)    print(result)    for x in result:        for y in x:            print(y)path = r"C:\Users\dell\Desktop\kt\test.json"output()

注意函數返回多個值時返回的是一個元組tuple;
對一個字串進行for迴圈的時候會對每個字元進行遍曆



Python JSON

本章節我們將為大家介紹如何使用 Python 語言來編碼和解碼 JSON 對象。

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,易於人閱讀和編寫。

JSON 函數

使用 JSON 函數需要匯入 json 庫:import json

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

json.dumps 用於將 Python 對象編碼成 JSON 字串。

文法
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)
執行個體

以下執行個體將數組編碼為 JSON 格式資料:

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

以上代碼執行結果為:

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

使用參數讓 JSON 資料格式化輸出:

>>> import json>>> print json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': ')){    "a": "Runoob",    "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.loads 用於解碼 JSON 資料。該函數返回 Python 欄位的資料類型。

文法
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
執行個體

以下執行個體展示了Python 如何解碼 JSON 對象:

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

以上代碼執行結果為:

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

json 類型轉換到 python 的類型對照表:

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

Demjson 是 python 的第三方模組庫,可用於編碼和解碼 JSON 資料,包含了 JSONLint 的格式化及校正功能。

Github 地址:https://github.com/dmeranda/demjson

官方地址:http://deron.meranda.us/python/demjson/

環境配置

在使用 Demjson 編碼或解碼 JSON 資料前,我們需要先安裝 Demjson 模組。本教程我們會下載 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 對象
encode

Python encode() 函數用於將 Python 對象編碼成 JSON 字串。

文法
demjson.encode(self, obj, nest_level=0)
執行個體

以下執行個體將數組編碼為 JSON 格式資料:

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

以上代碼執行結果為:

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

Python 可以使用 demjson.decode() 函數解碼 JSON 資料。該函數返回 Python 欄位的資料類型。

文法
demjson.decode(self, txt)
執行個體

以下執行個體展示了Python 如何解碼 JSON 對象:

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

以上代碼執行結果為:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。 http://blog.csdn.net/ko_tin/article/details/72472793

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.