在Python中使用JSON

來源:互聯網
上載者:User

在Python中使用JSON

在伺服器和用戶端的資料互動的時候,要找到一種資料格式,服務端好處理,用戶端也好處理,這種資料格式應該是一種統一的標準,不管在哪裡端處理起來都是統一的,現在這種資料格式非常的多,比如最早的xml,再後來較為流行的json。

JSON是什麼

JSON(JavaScript Object Notation, JS 對象標記) 是一種輕量級的資料交換格式。它基於 ECMAScript (w3c制定的js規範)的一個子集,採用完全獨立於程式設計語言的文字格式設定來儲存和表示資料。簡潔和清晰的階層使得 JSON 成為理想的資料交換語言。

JSON 比 XML 更小、更快,更易解析。

json格式如下:

{    "sites": [        {            "name": "幫客之家",            "url": "www.bkjia.com"        },        {            "name": "幫客之家交流社區",            "url": "www.bkjia.net"        },        {            "name": "linuxmi",            "url": "www.linuxmi.com"        }    ]}
python中如何解析json

既然json是一個通用的資料交換方式,那麼python中如何解析json呢?

在python中標準庫就能對json字串進行解析,同時把python的資料結構轉換為json格式字串。

把字串json解析為python的資料結構:

#!/usr/bin/python#coding=utf-8"""start python 項目"""import jsonif __name__ == '__main__':    jsonstr="""{    "sites": [        {            "name": "幫客之家",            "url": "www.bkjia.com"        },        {            "name": "幫客之家交流社區",            "url": "www.bkjia.net"        },        {            "name": "linux迷",            "url": "www.linuxmi.com"        }    ]    }"""    print jsonstr    sites = json.loads(jsonstr)    print sites    print sites['sites']    for site in sites['sites']:        print site['name'],site['url']

把python中的資料結構轉換為json格式:

#!/usr/bin/python#coding=utf-8"""start python 項目"""import jsonif __name__ == '__main__':    sites = {'sites':[{"name": "幫客之家","url": "www.bkjia.com"},{"name": "幫客之家交流社區","url": "www.bkjia.net"},{"name": "linux迷","url": "www.linuxmi.com"}]}    jsonstr = json.dumps(sites)    print jsonstr

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.