Python 提取绑定参数以构建JSON查询

Python 提取绑定参数以构建JSON查询,python,regex,json,rest,postman,Python,Regex,Json,Rest,Postman,我有一个从BIND导出的文件,其中包含大约500个域名的TSIG值。我需要将数据重新调整为JSON,用于RESTAPI查询。绑定数据的格式如下: // secondary-example.com. key "2000000000000.key." { algorithm hmac-md5; secret "ahashedvalue="; };

我有一个从BIND导出的文件,其中包含大约500个域名的TSIG值。我需要将数据重新调整为JSON,用于RESTAPI查询。绑定数据的格式如下:

            //  secondary-example.com.
            key "2000000000000.key." {
                algorithm hmac-md5;
                secret "ahashedvalue=";
            };

            zone "secondary-example.com." {
                type slave;
                file "sec/secondary-example.com.";
                allow-transfer { 1.1.1.1;
                                  1.1.2.2;
                                };
                 also-notify    { 1.1.1.1;
                                  2.2.2.2;
                                };
                 masters {
                   1.2.3.4 key 2000000000000.key.;
                 };
            };
从这里我需要提取密钥,区域和秘密。下面是一个示例API请求

            {  
               "properties":{  
                  "name":"secondary-example.com.",
                  "accountName":"example",
                  "type":"SECONDARY"
               },
               "secondaryCreateInfo":{  
                  "primaryNameServers":{  
                     "nameServerIpList":{  
                        "nameServerIp1":{  
                           "ip":"1.2.3.4",
                           "tsigKey":"2000000000000.key.",
                           "tsigKeyValue":"ahashedvalue="
                        }
                     }
                  }
               }
            }

我很难创建一个适合这个场景的正则表达式。我正在寻找用python脚本构建JSON并通过Postman发送请求。

我花了几天时间阅读regex并找到了解决方案。所以,每个“区域”都以一条评论开始。。。e、 g.“secondary example.com”。。。每一组绑定信息的长度正好是17行。这个解决方案是黑客攻击的,总是假设数据是正确的,但它成功地工作了

  • 将区域分隔为文本块

    zones = []
    cur_zone = ''
    f = open(bind_file).readlines()
    for line in f:
        if line[0:2] == '//':
            zones.append(cur_zone)
            cur_zone = ''
        else:
            cur_zone = cur_zone + line
    zones.pop(0) # Drop the first list item, it's empty
    
  • 迭代这些块并匹配所需的参数

    for z in zones:
        z_lines = z.splitlines()
        # Regex patterns to make the required parameters
        key = re.findall('\"(.*)\"', z_lines[0])[0]
        secret = re.findall('\"(.*)\"', z_lines[2])[0]
        name = re.findall('\"(.*)\"', z_lines[5])[0]
        master = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', z_lines[15])[0]
    

  • 您想要一个正则表达式模式来提取密钥、区域和机密?或者每个变量有一个模式,如
    键“*?”
    区域“*?”
    秘密“*?”
    ?@Rawing,谢谢回复。我明白了。我会将我的解决方案作为答案发布。