taotao.li
taotao.li

Reputation: 1082

difference between json.loads and python eval to trans string to json object

I use redis to store all the data in my small web app, there format is python dict or json object.

so I store them in redis as pure string, and want to get them and trans them as a dict/json object later to use.

but I find that I can use python eval to trans that string to dict, but cannot use json.loads().

From code bellow, it seems that it's because the format of string read from redis can't feed json, so it can be transformed using json.loads(json.dumps(data_in_redis)).

Here is my concern and problem

thanks a lot

In [6]: data_in_redis = r.hmget('dash_meta', '8')[0]

In [7]: data_in_redis
Out[7]: "{'id': 8, 'author': 'author-author', 'name': 'name-name', 'time_modified': 1444958866, 'desc': 'desc'}"

In [8]: eval(data_in_redis)
Out[8]:
{'author': 'author-author',
 'desc': 'desc',
 'id': 8,
 'name': 'name-name',
 'time_modified': 1444958866}

In [10]: import json

In [11]: json.loads(data_in_redis)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-3f228e0cf408> in <module>()
----> 1 json.loads(data_in_redis)

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, 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

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
    364
    365         """
--> 366         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    367         end = _w(s, end).end()
    368         if end != len(s):

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
    380         """
    381         try:
--> 382             obj, end = self.scan_once(s, idx)
    383         except StopIteration:
    384             raise ValueError("No JSON object could be decoded")

ValueError: Expecting property name: line 1 column 2 (char 1)

In [12]: json.dumps(data_in_redis)
Out[12]: '"{\'id\': 8, \'author\': \'author-author\', \'name\': \'name-name\', \'time_modified\': 1444958866, \'desc\': \'desc\'}"'

In [13]: json.loads(_)
Out[13]: u"{'id': 8, 'author': 'author-author', 'name': 'name-name', 'time_modified': 1444958866, 'desc': 'desc'}"

In [14]:

Upvotes: 2

Views: 1348

Answers (1)

Eric
Eric

Reputation: 97565

There're a bunch of things you should know:

  • Your database contains invalid json. You should find the code that writes to it, and ensure it uses json.dumps
  • Blindly textually replacing quotes does not work, in cases where the data itself contains quotes or apostrophes
  • eval shouldn't be used here. If you need to deal with the malformed data, use ast.literal_eval

Upvotes: 2

Related Questions