简体   繁体   中英

Convert Comma Separated String in Nested JSON to List Python

My JSON data looks like this:

   [{
        "coverageResponse": "100000\/500000\/1000000",
        "insuranceLine": "COMMERCIAL",
        "coverageCategory": "COVERAGE",
        "carriers": [{
            "carrierId": "LMICO",
            "states": "GA, CA",
            "excludedStates": "PA, NY"
        }, {
            "carrierId": "CNICO",
            "states": "NY, PA",
            "excludedStates": "CA, MI, OH"
        }]
    },
    {
        "coverageResponse": "222\/333\/111",
        "insuranceLine": "COMMERCIAL",
        "coverageCategory": "COVERAGE",
        "carriers": [{
            "carrierId": "LMICO",
            "states": "GA, CA",
            "excludedStates": "PA, NY"
        }, {
            "carrierId": "CNICO",
            "states": "NY, PA",
            "excludedStates": "CA, MI, OH"
        }]
    }]

I want states and excludedStates inside carriers to be in a list

Here is my output expectation:

 [{
        "coverageResponse": "100000\/500000\/1000000",
        "insuranceLine": "COMMERCIAL",
        "coverageCategory": "COVERAGE",
        "carriers": [{
            "carrierId": "LMICO",
            "states": ["GA, CA"],
            "excludedStates": ["PA, NY"]
        }, {
            "carrierId": "CNICO",
            "states": ["NY, PA"],
            "excludedStates": ["CA, MI, OH"]
        }]
    },
   {
    "coverageResponse": "222\/333\/111",
    "insuranceLine": "COMMERCIAL",
    "coverageCategory": "COVERAGE",
    "carriers": [{
        "carrierId": "LMICO",
        "states": "GA, CA",
        "excludedStates": "PA, NY"
    }, {
        "carrierId": "CNICO",
        "states": "NY, PA",
        "excludedStates": "CA, MI, OH"
    }]
}]

Solution for your problem:

init_json = #your json
for i, external in enumerate(init_json):
   for j, internal in enumerate(external['carriers']): 
      init_json[i]['carriers'][j]['states'] = internal['states'].split(', ')
      init_json[i]['carriers'][j]['excludedStates'] = internal['excludedStates'].split(', ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM