0

This is a sample JSON object in my JSON document:

[{
"_id": "COVERAGE_0025",
"coverageName": "windStormHailDeductible",
"coverageResponse": "15000",
"insuranceLine": "COMMERCIAL",
"coverageCategory": "DEDUCTIBLE",
"splitCoverages": null,
"carriers": [{
    "carrierId": "CNINCO",
    "states": null,
    "excludedStates": [
        "FL"
    ],
    "industries": null,
    "excludedIndustries": null,
    "products": [
        "BOP",
        "WC"
    ]
}]

I need to group everything except coverageName and _id inside coverages.

This is my desired output:

[{
    "_id": "COVERAGE_0025",
    "coverageName": "windStormHailDeductible",
    "coverages": [{
        "coverageResponse": "15000",
        "insuranceLine": "COMMERCIAL",
        "coverageCategory": "DEDUCTIBLE",
        "splitCoverages": null,
        "carriers": [{
            "carrierId": "CNINCO",
            "states": null,
            "excludedStates": [
                "FL"
            ],
            "industries": null,
            "excludedIndustries": null,
            "products": [
                "BOP",
                "WC"
            ]
        }]
    }]
}]

1 Answers1

0

What about something like:

fixed = ["_id","coverageName"]
d_new = {}
for elem in fixed:
    d_new[elem] = d[elem]

d_new["coverages"] = [{}]
for elem in d.keys():
    if elem not in fixed:
        d_new["coverages"][0][elem] = d[elem]

Output:

{'_id': 'COVERAGE_0025',
 'coverageName': 'windStormHailDeductible',
 'coverages': [{'coverageResponse': '15000',
   'insuranceLine': 'COMMERCIAL',
   'coverageCategory': 'DEDUCTIBLE',
   'splitCoverages': 'null',
   'carriers': [{'carrierId': 'CNINCO',
     'states': 'null',
     'excludedStates': ['FL'],
     'industries': 'null',
     'excludedIndustries': 'null',
     'products': ['BOP', 'WC']}]}]}
Let's try
  • 1,044
  • 9
  • 20
  • Though I don't know why, but he want to have a list of `coverages`... So I think you need to add the dict into a list. And, use `json.loads` and `json.dumps` maybe better. – Yang HG Sep 01 '20 at 08:05
  • Check the edit, you can just use `json.dumps` and `json.loads` before and after as you want. Check [here](https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file) for example – Let's try Sep 01 '20 at 09:41