Python:用另一个字符替换转义引号

标签 python json regex parsing double-quotes

我有一个包含 HTML 的 JSON,我需要使其可解析。 Pandas 无法导入这种 JSON。

text = """[{
   "article_id": 3540349,
   "site_id": 1563,
   "domain": "https:\/\/ear.rt.hm",
   "code": "wta-jurmala-benara-u-ctrtl",
   "uri": "https:\/\/ar.rl.hq\/spormala-berera-u-cetinalu\/",
   "content_type": {
       "id": 1,
       "name": "article"
   },
   "article_type": {
       "id": 1,
       "name": "article"
   },
   "created": "2019-07-25 23:58:20",
   "modified": "2019-07-25 23:59:19",
   "publish_date": "2019-07-25 23:58:00",
   "active": true,
   "author": "<a href=\"https:\/\/spt02.com\" target=\"_blank\">I 
Kapri<\/a>"
}]"""

text = text.replace('\"', "'")

结果是(不考虑文本差异):

'author': '<a href='https:\/\/spo.hq' target='_blank'>Iv<\/a>'

当我尝试替换 '\"' 时,我得到:

"author": "<a href="https:\/\/spr.hq" target="_blank">Ilari<\/a>"

这又不是我想要的。

有谁知道如何正确地将\"转义为 ' ?

最佳答案

问题是你在不应该的时候转义了这些\字符。通过在 """之前添加 r 来使用原始字符串

import json
text = r"""[{
   "article_id": 35449,
   "site_id": 153,
   "domain": "https:\/\/ezt.hq",
   "code": "wta-jurrda-pe-cetlu",
   "uri": "https:\/\/ezl.hr\/s0349\/wla-balu\/",
   "content_type": {
       "id": 1,
       "name": "article"
   },
   "article_type": {
       "id": 1,
       "name": "article"
   },
   "created": "2019-07-25 23:58:20",
   "modified": "2019-07-25 23:59:19",
   "publish_date": "2019-07-25 23:58:00",
   "active": true,
   "author": "<a href=\"https:\/\/spr2.hr\" target=\"_blank\">Iari<\/a>"
}]"""
obj = json.loads(text)

如果您从 txt 文件中读取文本,请将 text = r"""...""" 替换为 text = open(file_name).read()

关于Python:用另一个字符替换转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58603459/

相关文章:

python - MongoDB、MongoEngine : unique list items

c# - 帮助正则表达式。需要提取 `<A HREF`

javascript - 仅查找并获取字符串中的数字

php - 如何使用正则表达式在最后一次模式出现后捕获字符?

python - Python中列表列表的简单聚类

python - boolean 测试 Python 中的列表

python - 命名组内的非捕获组

javascript - 带有内联日期选择器(日历)的 JSON 数据类型

javascript - 从 Json 数据异步加载 Google map 标记

json - 从 JSON 文件中删除换行符、制表符和回车符等转义序列字符