ハマったので備忘。
ヒアドキュメントにそのままエスケープシーケンス(\
)を書いてもエスケープシーケンスとして展開されない。
\\
のように2つ続けて記述するか、raw文字列を使うと展開できる。
>>> import json
>>>
>>> json_dict1 = json.loads('''
... {
... "id": 1,
... "name": "hoge",
... "description": "ほげ\"ほげ\"ほげ"
... }
... ''')
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",
... "description": "ほげ\\"ほげ\\"ほげ"
... }
... ''')
>>> print(json_dict2)
{'id': 2, 'name': 'hoge', 'description': 'ほげ"ほげ"ほげ'}
>>>
>>> json_dict3 = json.loads(r'''
... {
... "id": 3,
... "name": "hoge",
... "description": "ほげ\"ほげ\"ほげ"
... }
... ''')
>>> print(json_dict3)
{'id': 3, 'name': 'hoge', 'description': 'ほげ"ほげ"ほげ'}