如何修复此正则表达式以匹配Json中的对象并将其替换为Object列表

问题描述 投票:0回答:2

我尝试过以下但是我无法匹配Json中的对象

:\s*(\{[^\"]*\})

我想知道将Json中的对象类型替换为对象列表的方法。

以下是Json的示例:

{
  "resourceType": "ChargeItem",
  "id": "example",
  "text": {
    "status": "generated",
    "session": "Done"
  },
  "identifier": [
    {
      "system": "http://myHospital.org/ChargeItems",
      "value": "654321"
    }
  ],
  "definitionUri": [
    "http://www.kbv.de/tools/ebm/html/01520_2904360860826220813632.html"
  ],
  "status": "billable",
  "code": {
    "coding": [
      {
        "code": "01510",
        "display": "Zusatzpauschale für Beobachtung nach diagnostischer Koronarangiografie"
      }
    ]
  }
}

我需要转换为这种形式:

{
  "resourceType": "ChargeItem",
  "id": "example",
  "text": [{
    "status": "generated",
    "session": "Done"
  }],
  "identifier": [
    {
      "system": "http://myHospital.org/ChargeItems",
      "value": "654321"
    }
  ],
  "definitionUri": [
    "http://www.kbv.de/tools/ebm/html/01520_2904360860826220813632.html"
  ],
  "status": "billable",
  "code": [{
    "coding": [
      {
        "code": "01510",
        "display": "Zusatzpauschale für Beobachtung nach diagnostischer Koronarangiografie"
      }
    ]
  }]
}

python json regex string
2个回答
0
投票

这似乎是一些简单的转换:

首先,改变

"text": {

"text": [{

第二,改变

},
"identifier": [

}],
"identifier": [

第三,改变

 "code": {

 "code": [{

最后,改变

  }
}
<EOF>

  }]
}
<EOF>

然而,它可能不像它看起来那么简单,即如果identifer部分不总是存在,或者不立即跟随text部分怎么办?

正则表达式是做这项工作的不良选择。将json文件读入本机Python数据结构,应用所需的更改,然后将json保存回文件会好得多。


0
投票

使用多行正则表达式搜索的解决方案

>>> import re

>>> blocks = re.compile(r'(?ms)(.*)("text": )([{][^{}]+[}])(,.*"status": "billable"[^"]+)("code": )([{][^"]+"coding":[^]]+\]\s+\})')
>>> m = blocks.search(s)
>>> result = ""
>>> for i in range(1,len(m.groups()) + 1):
...   if i not in (3,6):
...     result += m.group(i)
...   else:
...     result += "[" + m.group(i) + "]"
... 
>>> result += "\n}"
© www.soinside.com 2019 - 2024. All rights reserved.