如何正确地转义JSON中的保留regex字符?

2024-06-26 14:12:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,其中包含一些我想在python代码中使用的regex表达式。 当我试图转义JSON文件中的保留regex字符时,问题就出现了。 当我运行python代码时,它无法处理json文件并抛出异常。你知道吗

我已经调试了代码并得出结论,调用json.loads(ruleFile.read())时它失败了。显然,在JSON中只有一些字符可以转义,而点不是其中之一,这会导致语法错误。你知道吗

try:
    with open(args.rules, "r") as ruleFile:
        rules = json.loads(ruleFile.read())
        for rule in rules:
            rules[rule] = re.compile(rules[rule])
except (IOError, ValueError) as e:
    raise Exception("Error reading rules file")
{
    "Rule 1": "www\.[a-z]{3,10}\.com"
}
Traceback (most recent call last):
  File "foo.py", line 375, in <module>
    main()
  File "foo.py", line 67, in main
    raise Exception("Error reading rules file")
Exception: Error reading rules file

如何解决这个JSON语法问题?你知道吗


Tags: 文件代码injsonexceptionerror字符rule
2条回答

反斜杠需要在JSON中转义。你知道吗

{
    "Rule 1": "www\\.[a-z]{3,10}\\.com"
}

here

The following characters are reserved in JSON and must be properly escaped to be used in strings:

  • Backspace is replaced with \b
  • Form feed is replaced with \f
  • Newline is replaced with \n
  • Carriage return is replaced with \r
  • Tab is replaced with \t
  • Double quote is replaced with \"
  • Backslash is replaced with \\

规则是首先在正确的字典中有一个正确的字符串。和\在Python中是转义符。你知道吗

所以你应该先写:

rules = {"Rule 1": r"www\.[a-z]{3,10}\.com"}

然后可以轻松地将其转换为JSON字符串:

print(json.dumps(rules, indent=4))

{
    "Rule 1": "www\\.[a-z]{3,10}\\.com"
}

现在您知道了包含regex的json文件应该如何格式化。你知道吗

相关问题 更多 >