码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-05-06 13:19:57      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:ini   注意   obj   file   ext   bsp   转换   字符串   span   

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前缀修饰符去掉
 
 
 
 
 
 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

标签:ini   注意   obj   file   ext   bsp   转换   字符串   span   

原文地址:http://www.cnblogs.com/zejin2008/p/6816289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!