将嵌套 JSON 中的逗号分隔字符串转换为列表 Python

我的 JSON 数据如下所示:


   [{

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

        }]

    }]

我希望states里面excludedStates的内容carriers出现在列表中


这是我的输出期望:


 [{

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

    }]

}]


一只名叫tom的猫
浏览 112回答 1
1回答

弑天下

您的问题的解决方案:init_json = #your jsonfor 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(', ')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python