Python中json.loads处理转义字符报错的解决求助
问题分析与解决方案
错误根源
- JSON语法不规范:你的
input_json中content字段包含未转义的双引号(比如"Eh? Wer bist denn Du?"),JSON要求字符串内部的双引号必须用\"转义,否则解析器会误判为字符串结束标志,触发Invalid \escape错误。 - 错误的字符串格式化操作:使用
"""{}""".format(input_json)会破坏JSON结构——format会尝试解析字符串中的{}占位符,而JSON本身就包含大量{},导致格式混乱。
修复步骤
步骤1:修正JSON字符串的转义问题
将content字段内的所有未转义双引号替换为\",修正后的JSON字符串如下:
input_json = '''{"id": 109504954315901999, "created_at": "2022-12-13T06:29:58+00:00", "in_reply_to_id": null, "in_reply_to_account_id": null, "sensitive": false, "spoiler_text": "", "visibility": "public", "language": "de", "uri": "https://troet.cafe/users/TGamay/statuses/109504954282374823", "url": "https://troet.cafe/@TGamay/109504954282374823", "replies_count": 0, "reblogs_count": 0, "favourites_count": 0, "edited_at": null, "content": "<p>13. Dez: \\"Eh? Wer bist denn Du? Willste etwa Koks haben? Das kannste vergessen. So wie Du aussiehst, hast Du auch gar keins nötig. Dein Bart ist ja noch ganz weiß. Hast Dir wohl grad die Markierungslinie der Autobahn reingezogen, was? Hehehe.\\"<br>Dem Weihnachtsmann gefiel der Humor.</p>", "reblog": null, "account": {"id": 108218397610933167, "username": "TGamay", "acct": "TGamay@troet.cafe", "display_name": "TGamay", "locked": false, "bot": false, "discoverable": true, "group": false, "created_at": "2022-04-25T00:00:00+00:00", "note": "<p>Eine Perlenkette von Lichtern erschien mir. Seitdem bin ich bei Mastodon. Summa Rudis</p>", "url": "https://troet.cafe/@TGamay", "avatar": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "avatar_static": "https://files.mastodon.social/cache/accounts/avatars/108/218/397/610/933/167/original/2019387a4907e0ce.jpg", "header": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "header_static": "https://files.mastodon.social/cache/accounts/headers/108/218/397/610/933/167/original/6ebd292535d3f7b1.jpg", "followers_count": 159, "following_count": 381, "statuses_count": 603, "last_status_at": "2022-12-13T00:00:00", "emojis": [], "fields": []}, "media_attachments": [], "mentions": [], "tags": [], "emojis": [], "card": null, "poll": null}'''
步骤2:正确解析JSON
直接将修正后的input_json传入json.loads,无需额外的字符串格式化操作:
import json data = json.loads(input_json)
额外提示
- 如果
input_json是从API或文件获取的,确保来源返回标准JSON格式,无需手动修改转义符。 - 避免用字符串格式化处理JSON数据,直接传递原始字符串即可,防止破坏结构。
内容的提问来源于stack exchange,提问作者deepu2711
相关产品推荐
相关产品推荐

