JSON有兩種結構:python
eval與json.loads均可以將大部分的JSON串轉成Python對象,但也有區別:json
>>> import json >>> s = '{"one":1,"two":2}' >>> json.loads(s) {u'two': 2, u'one': 1} >>> eval(s) {'two': 2, 'one': 1}
json.loads與eval都能將s轉成python中的對象,json.loads將json中的字符串轉成unicode(types.UnicodeType),eval轉成了str(types.StringType)。在讀文件時若是有中文如數組
此時用json.loads會報錯以下:python2.7
這時使用eval不會報錯,強烈推薦,這個問題困擾了我一夜。.net
對於普通的數據類型,json.loads和eval都能用,但:code
>>> x="[null,true,false,1]" >>> json.loads(x) [None, True, False, 1] >>> eval(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'null' is not defined
在遇到特殊類型的時候,eval就無論用了。eval一般用來執行一個字符串表達式,並返回表達式的值。好比:對象
>>> eval('1+1') 2 >>> json.loads('1+1') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 368, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 1 column 2 - line 1 column 4 (char 1 - 3)
json字符串轉python對象的數據類型轉換表 python對象轉json字符串類型轉換表ci
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
>>> dct = {'one':None,'two':2} >>> json.dumps(dct) '{"two": 2, "one": null}'
>>> arry = [True, False, 'hello'] >>> json.dumps(arry) '[true, false, "hello"]'
另,須要注意的是:unicode
>>> dct="{'one':1}" >>> json.loads(dct) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 2 (char 1)
報錯是由於json不認單引號,json中的字符串須要用雙引號包起來。字符串