programing

Python에서 JSON을 문자열로 변환

codeshow 2023. 3. 8. 21:38
반응형

Python에서 JSON을 문자열로 변환

나는 처음에 내 질문을 명확하게 설명하지 않았다.사용해보십시오.str()그리고.json.dumps()JSON을 python 문자열로 변환할 때 사용합니다.

>>> data = {'jsonKey': 'jsonValue',"title": "hello world"}
>>> print json.dumps(data)
{"jsonKey": "jsonValue", "title": "hello world"}
>>> print str(data)
{'jsonKey': 'jsonValue', 'title': 'hello world'}
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world"}'
>>> str(data)
"{'jsonKey': 'jsonValue', 'title': 'hello world'}"

질문입니다.

>>> data = {'jsonKey': 'jsonValue',"title": "hello world'"}
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': "hello world\'"}'
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\'"}'
>>> 

예상 출력:"{'jsonKey': 'jsonValue','title': 'hello world''}"

>>> data = {'jsonKey': 'jsonValue',"title": "hello world""}
  File "<stdin>", line 1
    data = {'jsonKey': 'jsonValue',"title": "hello world""}
                                                          ^
SyntaxError: EOL while scanning string literal
>>> data = {'jsonKey': 'jsonValue',"title": "hello world\""}
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\\""}'
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': \'hello world"\'}'

예상 출력:"{'jsonKey': 'jsonValue','title': 'hello world\"'}"

출력 문자열을 다시 json(dict)으로 변경할 필요는 없습니다.

이거 어떻게 하는 거야?

json.dumps() Python 오브젝트로 스트링을 만드는 것 이상입니다.Type Conversion Table 에 항상 유효한 JSON 스트링이 생성됩니다(오브젝트 내의 모든 것이 시리얼화 가능하다고 가정).

예를 들어 값 중 하나가None,그str()로딩할 수 없는 비활성 JSON이 생성됩니다.

>>> 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)

근데...dumps()변환하다None안으로null로드할 수 있는 유효한 JSON 문자열을 만듭니다.

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

다른 차이점이 있습니다.예를 들어.{'time': datetime.now()}는 JSON으로 시리얼화할 수 없지만 문자열로 변환할 수 있습니다.목적에 따라 이러한 도구 중 하나를 사용해야 합니다(즉, 결과가 나중에 디코딩됩니다).

언급URL : https://stackoverflow.com/questions/34600003/converting-json-to-string-in-python

반응형