python json dumps与loads有可能犯的错误

json.dumps() 是将一个Python数据结构转换为一个JSON编码的字符串
json.loads() 是将一个JSON编码的字符串转换为一个Python数据结构
 
 
如下:
>>> import json
>>> a={'name':'xiaoming'}
>>> json.dumps(a)
'{"name": "xiaoming"}'
>>> b='{"name": "xiaoming"}'
>>> json.loads(b)
{u'name': u'xiaoming'}
 
 
注意:我们原先定义a的元素都是用单引号,而dumps转化后都变成了双引号,而在loads后变成python变量时,元素都变成了单引号,并且字符串前加多了个u。
 
那么当我定义如下的字符串类型时,元素内容用单引号,而整个字符串用双引号括起来:
>>> c="{'name':'xiaoming'}"
>>> print json.loads(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python27/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/python27/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python27/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
 
程序报错了,所以一般要求当要字符串通过loads转为python数据类型时,得外层用单引号,里面元素key和value用双引号
 
还有,即使满足上述条件,当有u前缀的unicode出现修饰时,也会报错:
>>> c='{u"name": u"xiaoming"}'
>>> json.loads(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python27/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/python27/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python27/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
 
所以loads在处理中,还需要把里面的u前缀修饰符去掉
 
 
 
 
 https://stackoverflow.com/questions/25707558/json-valueerror-expecting-property-name-line-1-column-2-char-1
 
 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
posted @ 2017-05-06 12:05  泽锦  阅读(12446)  评论(0编辑  收藏  举报