詳解python中的json的基本使用方法_python

來源:互聯網
上載者:User

在Python中使用json的時候,主要也就是使用json模組,json是以一種良好的格式來進行資料的互動,從而在很多時候,可以使用json資料格式作為程式之間的介面。

#!/usr/bin/env python #-*- coding:utf-8 -*- import json  print json.load(open('kel.txt')) #deserialize string or unicode to python object j = json.loads(open('kel.txt').read(),encoding='utf-8') print type(j),j for i in j:   print i k = json.dumps(j,encoding='utf-8').decode('utf-8') print k 

kel.txt檔案內容如下:

{   "中文":"kel",   "fist":"kel" } 


執行結果如下:

{u'\u4e2d\u6587': u'kel', u'fist': u'kel'} <type 'dict'> {u'\u4e2d\u6587': u'kel', u'fist': u'kel'} 中文 fist {"\u4e2d\u6587": "kel", "fist": "kel"} 

在其中主要使用的方法為json.loads和json.dumps

注意在loads中參數必須為string,從而在開啟檔案的時候,要使用read方法,否則會出錯。

loads方法主要是用來載入json資料變成python中的對象,而dumps方法主要是將python對象修改為json格式。

開始遇到一個錯誤如下:

[root@python 56]# python kel.py  Traceback (most recent call last):  File "kel.py", line 5, in <module>   json.load(open('kel.txt'))  File "/usr/local/python/lib/python2.7/json/__init__.py", line 291, in load   **kw)  File "/usr/local/python/lib/python2.7/json/__init__.py", line 339, in loads   return _default_decoder.decode(s)  File "/usr/local/python/lib/python2.7/json/decoder.py", line 364, in decode   obj, end = self.raw_decode(s, idx=_w(s, 0).end())  File "/usr/local/python/lib/python2.7/json/decoder.py", line 382, in raw_decode   raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded 

主要原因是因為,,,在json的資料格式中必須是雙引號開頭的,錯誤的json檔案如下:

 {   "fist":'kel' } 

kel.py內容如下:

 #!/usr/bin/env python #-*- coding:utf-8 -*- import json j = json.loads(open('kel.txt').read()) print type(j),j     

雙引號。。。單引號,傻傻的分不清楚

有的時候,在進行loads方法的時候,就是因為產生了單引號的字串。。。在python中尤其如此,和其他的東西沒啥關係,主要就是引號的關係!!!

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

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