python版本2.7.5
http://
事情是这样的,本来数据库中存了一个str字段(是一个url集合),现在需要取出来,把url一个一个的显示。
用sql取出来以后得到的字段值像这样;
In [24]: test
Out[24]: u"{u‘29217‘: u‘http://pmt.wdjcdn.com‘}"这个字符串猛一看像是json格式,于是直接用python解析了,看看如下的结果:
In [25]: import json
In [26]: json.loads(test)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-26-917bdd56b2fa> in <module>()
----> 1 json.loads(test)
D:\devsofts\python2.7\lib\json\__init__.pyc in loads(s, encoding, cls, object_ho
ok, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
336 parse_int is None and parse_float is None and
337 parse_constant is None and object_pairs_hook is None and not
kw):
--> 338 return _default_decoder.decode(s)
339 if cls is None:
340 cls = JSONDecoder
D:\devsofts\python2.7\lib\json\decoder.pyc in decode(self, s, _w)
363
364 """
--> 365 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
366 end = _w(s, end).end()
367 if end != len(s):
D:\devsofts\python2.7\lib\json\decoder.pyc in raw_decode(self, s, idx)
379 """
380 try:
--> 381 obj, end = self.scan_once(s, idx)
382 except StopIteration:
383 raise ValueError("No JSON object could be decoded")
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (
char 1)
In [27]: eval(test)
Out[27]: {u‘29217‘: u‘http://pmt.wdjcdn.com‘}结果倒是正常了。
那么这个dict存储为字符串的形式和json有什么不同呢?
In [28]: json.dumps(eval(test)) #转化为json
Out[28]: ‘{"29217": "http://pmt.wdjcdn.com"}‘
In [29]: test
Out[29]: u"{u‘29217‘: u‘http://pmt.wdjcdn.com‘}"In [33]: str(eval(test)) #这就是原来的字符串
Out[33]: "{u‘29217‘: u‘http://pmt.wdjcdn.com‘}"在有些代码中看到有人使用eval来解析从客户端传来的json,这样做可能也有些不妥,具体可以参见下
[python]json.load() vs val()探究
原文:http://blog.csdn.net/orangleliu/article/details/19815845