如何修复这个regex以匹配Json中的对象并将其替换为Obj列表

2024-05-16 21:46:48 发布

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

我尝试了以下方法,但未能匹配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"
      }
    ]
  }]
}


Tags: 对象textidjsonhttpexamplesessionhtml
2条回答

使用多行regexp搜索的解决方案

>>> 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}"

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

首先,改变

"text": {

"text": [{

第二,改变

},
"identifier": [

}],
"identifier": [

第三,改变

 "code": {

 "code": [{

最后,改变

  }
}
<EOF>

  }]
}
<EOF>

但是,它可能不像看上去那么简单,即如果identifer部分并不总是存在,或者没有立即跟随text部分,该怎么办?你知道吗

正则表达式是做这项工作的一个糟糕的选择。最好将json文件读入本地Python数据结构,应用所需的更改,然后将json保存回该文件。你知道吗

相关问题 更多 >