converting json to string in python

后端 未结 2 753
不知归路
不知归路 2020-12-04 17:37

I did not explain my questions clearly at beginning. Try to use str() and json.dumps() when converting json to string in python.

&         


        
相关标签:
2条回答
  • 2020-12-04 17:46

    json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

    For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

    >>> data = {'jsonKey': None}
    >>> str(data)
    "{'jsonKey': None}"
    >>> json.loads(str(data))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
        return _default_decoder.decode(s)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
        obj, end = self.scan_once(s, idx)
    ValueError: Expecting property name: line 1 column 2 (char 1)
    

    But the dumps() would convert None into null making a valid JSON string that can be loaded:

    >>> import json
    >>> data = {'jsonKey': None}
    >>> json.dumps(data)
    '{"jsonKey": null}'
    >>> json.loads(json.dumps(data))
    {u'jsonKey': None}
    
    0 讨论(0)
  • 2020-12-04 17:47

    There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

    0 讨论(0)
提交回复
热议问题