I'm addicted to it, so I'll take note of it.
Even if the escape sequence (\) is written as it is in the here document, it is not expanded as an escape sequence.
It can be expanded by writing two in a row like \\ or by using a raw string.
>>> import json
>>>
>>> json_dict1 = json.loads('''
... {
... "id": 1,
... "name": "hoge",
... "discription": "Hoge\"Hoge\"Hoge"
... }
... ''')
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 5 column 24 (char 59)
>>> print(json_dict1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'json_dict1' is not defined
>>>
>>> json_dict2 = json.loads('''
... {
... "id": 2,
... "name": "hoge",
... "discription": "Hoge\\"Hoge\\"Hoge"
... }
... ''')
>>> print(json_dict2)
{'id': 2, 'name': 'hoge', 'discription': 'Hoge"Hoge"Hoge'}
>>>
>>> json_dict3 = json.loads(r'''
... {
... "id": 3,
... "name": "hoge",
... "discription": "Hoge\"Hoge\"Hoge"
... }
... ''')
>>> print(json_dict3)
{'id': 3, 'name': 'hoge', 'discription': 'Hoge"Hoge"Hoge'}
Recommended Posts