-1

I came across this json, I'm having trouble with such keys 3[0].1, 3[1].1, etc.(Field Repeat Seperator - HL7). The key 3.1 is split into two to accomodate another value. Similarly 3.4 & 3.5.

I want create a scalable program in which I can handle all these keys within "fields": {}.

{
    "fields": {
        "0": "A",
        "3[0].1": "B",
        "3[0].5": "C",
        "3[1].1": "D",
        "3[1].4": "E",
        "3[1].5": "F",
        "5.1": "E",
        "5.2": "G",
        "7": "H",
        "8": "I",
        "18": "J"
    }
}

Is it possible to loop through these values? I want to transform this to another output

{
    "setId": 0,
    "fields": {
        "3.1": "B",
        "3.5": "C",
     }
},
{
    "setId": 1,
    "fields": {
        "3.1": "D",
        "3.4": "E",
        "3.5": "F",
     }
}

1 Answers1

1

I am sure it could be done simpler

import json
from io import StringIO
a = """{
    "fields": {
        "0": "A",
        "3[0].1": "B",
        "3[0].5": "C",
        "3[1].1": "D",
        "3[1].4": "E",
        "3[1].5": "F",
        "5.1": "E",
        "5.2": "G",
        "7": "H",
        "8": "I",
        "18": "J"
    }
}"""

j = json.loads(a)
f = j["fields"]
set_ids = set([i[2] for i in f.keys() if i.startswith("3[")])

out = []

for set_id in set_ids:
    buf = {}
    buf["setId"] = set_id
    buf["fields"] = {}
    for x in filter(lambda x: x.startswith(f"3[{set_id}]"), f.keys()):
        buf["fields"][".".join([x[0], x[-1]])] = f[x]
    out.append(buf)

print(out)

Which outputs

[{'setId': '0', 'fields': {'3.1': 'B', '3.5': 'C'}}, {'setId': '1', 'fields': {'3.1': 'D', '3.4': 'E', '3.5': 'F'}}]
crayxt
  • 2,367
  • 2
  • 12
  • 17