如何使用python格式化/更新json中的无效数据



我的函数以json格式返回低于'jdata',这是无效的。我发现它在"collection_id"中具有无效值:,如何将"collection_id"的值设置为"或0,以便我可以解析下面的json。

jdata = 
{
    "status": {
        "state1": "retrying",
        "state2": "poll",
    },
    "conn_info": {
        "version": "0.0",
        "protocol_config": {
            "check_conp": false,
            "max_tunnel_i": 0,
            "collection_id": ,
            "descriptor": 0,
            "signature_key": "",
            "protocol_switching_policy": "udp_only",
            "udp_signaling_config": {
                "polling_t": 0,
                "polling_de": 0,
                "retry_gr": 0,
                "rwindow": 0,
                "status_ra": 0,
                "ud": 0,
                "server": "round_robin",
                "server": []
            }
        }

我使用了以下代码:

import json
def test_statusinfo():
    s = jdata
    try:
        decodedinfo = json.loads(s)
        for x in decodedinfo:
            if x == "conn_info":
                return decodedinfo[x]
    except(ValueError, KeyError, TypeError):
        LOGGER.info("JSON format error")
Error : JSON format error

使用 replace 命令来验证数据,现在我可以解析它了。在尝试块之前添加了以下代码:

if s.endswith('"collection_id": '):
    s= s.replace('"collection_id": ','"collection_id": 0')

最新更新