如何使用Python在json文件中查找和替换所有出现的json字典?

时间:2016-04-08 01:44:28

标签: python json regex parsing

我正在尝试用另一个字典替换json文件中所有出现的以下json字典:

要替换的字典

{
   "AP": {
           "UFD": xxx,
           "DF": "xxxxxx"
         },
   "IE": xxxx,
   "$": "PDAE"
}

要替换为

的字典
{
   "FileNameModifierItemPosition": 1,
   "FileNameModifierItemType": 0,
   "FileNameModifierParameters": {
                                  "DateParameters": {
                                                      "DT": 0,
                                                      "UFD": true,
                                                      "DF": "yyyyMMdd"
                                                    },
                                  "FqlParameters":  {
                                                      "FExpression": null
                                                    }
                                 },
    "IE": true,
    "$": "PDMFN
}

但我希望能够解析要替换的字典并提取IE,UFD,DF的值并分配给第二个字典中的corressponding字段。如何使用正则表达式在Python中完成此操作?

1 个答案:

答案 0 :(得分:1)

编辑请尝试以下方法:

import re
# pattern to get values of UFD, DF, and IE from dict1
p1 = '(?s){\s+"AP":\s+{\s+"UFD":\s+(.*?),\s+"DF":\s+"(.*?)"\s+},\s+"IE":\s+(.*?),\s+"\$":\s+"PDAE"\s+}'
# pattern to match dict2
p2 = '({[\s\S]+?"UFD":\s+)(.*?)(,\s+"DF":\s+")(.*?)("[\s\S]+?"IE":\s+)(.*?)(,[\s\S]+?})'

dict1 = """
{
   "AP": {
           "UFD": xxx,
           "DF": "xxxxxx"
         },
   "IE": xxxx,
   "$": "PDAE"
}
"""

dict2 = """
{
   "FileNameModifierItemPosition": 1,
   "FileNameModifierItemType": 0,
   "FileNameModifierParameters": {
                                  "DateParameters": {
                                                      "DT": 0,
                                                      "UFD": true,
                                                      "DF": "yyyyMMdd"
                                                    },
                                  "FqlParameters":  {
                                                      "FExpression": null
                                                    }
                                 },
    "IE": true,
    "$": "PDMFN
}
"""
# retrieve values from dict1
dict1_values = re.findall(p1, dict1)[0]
# replace dict2 with corressponding values from dict1
print re.sub(p2, r'\1%s\3%s\5%s\7' % dict1_values, dict2)

输出:

{
   "FileNameModifierItemPosition": 1,
   "FileNameModifierItemType": 0,
   "FileNameModifierParameters": {
                                  "DateParameters": {
                                                      "DT": 0,
                                                      "UFD": xxx,
                                                      "DF": "xxxxxx"
                                                    },
                                  "FqlParameters":  {
                                                      "FExpression": null
                                                    }
                                 },
    "IE": xxxx,
    "$": "PDMFN
}