abstract:本篇文章主要介紹了python中的json的基本使用方法,在Python中使用json的時(shí)候,主要也就是使用json模塊,json是以一種良好的格式來進(jìn)行數(shù)據(jù)的交互,有興趣的可以了解一下。在Python中使用json的時(shí)候,主要也就是使用json模塊,json是以一種良好的格式來進(jìn)行數(shù)據(jù)的交互,從而在很多時(shí)候,可以使用json數(shù)據(jù)格式作為程序之間的接口。#!/usr/bin/env py
本篇文章主要介紹了python中的json的基本使用方法,在Python中使用json的時(shí)候,主要也就是使用json模塊,json是以一種良好的格式來進(jìn)行數(shù)據(jù)的交互,有興趣的可以了解一下。
在Python中使用json的時(shí)候,主要也就是使用json模塊,json是以一種良好的格式來進(jìn)行數(shù)據(jù)的交互,從而在很多時(shí)候,可以使用json數(shù)據(jù)格式作為程序之間的接口。
#!/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文件內(nèi)容如下:
{ "中文":"kel", "fist":"kel" }
執(zhí)行結(jié)果如下:
{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中參數(shù)必須為string,從而在打開文件的時(shí)候,要使用read方法,否則會(huì)出錯(cuò)。
loads方法主要是用來加載json數(shù)據(jù)變成python中的對(duì)象,而dumps方法主要是將python對(duì)象修改為json格式。
開始遇到一個(gè)錯(cuò)誤如下:
[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
主要原因是因?yàn)?,,,在json的數(shù)據(jù)格式中必須是雙引號(hào)開頭的,錯(cuò)誤的json文件如下:
{ "fist":'kel' }
kel.py內(nèi)容如下:
#!/usr/bin/env python #-*- coding:utf-8 -*- import json j = json.loads(open('kel.txt').read()) print type(j),j
雙引號(hào)。。。單引號(hào),傻傻的分不清楚
有的時(shí)候,在進(jìn)行l(wèi)oads方法的時(shí)候,就是因?yàn)楫a(chǎn)生了單引號(hào)的字符串。。。在python中尤其如此,和其他的東西沒啥關(guān)系,主要就是引號(hào)的關(guān)系?。?!
更多關(guān)于python中的json的基本使用方法請(qǐng)關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!