python正则匹配并删除json字符串中的某个字段

时间:2025-03-02 07:07:36

这里写目录标题

  • 问题
  • 代码
  • 结语

问题

今天遇到一个需求,字符串类似

"{ 'form_view_ref' : 'hr_expense.hr_expense_view_form_without_header'    ,'default_employee_id': employee_id,    'default_company_id': company_id}"

这并不是标准的json字符串,因为其中含有变量,所以无法使用将其转为字典。需求是将form_view_ref这个字段的键值对删除。又想到可以使用eval函数,先将其中的变量声明赋值,再转为dict删除form_view_ref键值对后再转为json字符串。但是这样无论如何json字符串的字段都会含有双引号,真tm操性。老子直接上正则。

代码

import re

context = "{ 'form_view_ref' : 'hr_expense.hr_expense_view_form_without_header'    ,'default_employee_id': employee_id,    'default_company_id': company_id}"


def remove_item(string: str, key: str) -> str:
    string = string.lstrip(" ").rstrip(" ").lstrip("{").rstrip("}")
    key_pattern = ".+" + key + ".+"
    # 这种情况是指定字段不在最后,有逗号的时候
    replace_pattern_first = re.compile(f"[\'\"]{key}?[\'\"].+?:.+?[\'\"].+?[\'\"][^,]+,")
    # 这种情况是指定字段在最后,没有逗号的时候
    replace_pattern_second = re.compile(f"[\'\"]{key}?[\'\"].+?:.+?[\'\"].+?[\'\"][^,]?")
    if not re.match(key_pattern, string):
        raise Exception("嗨害")
    string = re.sub(replace_pattern_first, "", string)
    string = re.sub(replace_pattern_second, "", string)
    string = "{" + string.lstrip(" ").rstrip(" ").rstrip(",").rstrip(" ") + "}"
    return string


print(remove_item(context, "form_view_ref"))

结语

正则真的很难写,而且很难测,而且真的很难写,而且很难测。