首页 > 代码库 > python json dumps与loads有可能犯的错误
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前缀修饰符去掉
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
python json dumps与loads有可能犯的错误
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。