繁体   English   中英

如何使用python将json文件的选定部分解析为有效的json格式?

[英]How to parse selected section of json file into valid json format using python?

我有一个sample.json文件,如下所示:

{  
     "testA":
        {
            "testid":123,
            "placed":"C:/test/testA"     
        },
     "testB":
        {
            "testid":456,
            "placed":"C:/test/testB"     
        },
     "testC":
        {
            "testid":789,
            "placed":"C:/test/testC"     
        },
     "testD":
        {
            "testid":101,
            "placed":"C:/test/testD"     
        }
    }

我必须获取每个测试部分的testid并从以下代码中获取它:

    {
    "Output" :{
     "test_Idlist":[
    "123",
    "456",
    "789",
    "101"
    ]
    },
     "ReturnCode": "OK"
    }

我做了以下脚本:

   with open("c:/sample.json", 'r') as f:
        data = json.load(f)
    out = data
    ret_val = '{'+"\n"+'"Output" :{\n "test_Idlist":[\n';
    for val in out:
        ret_val += '"'+val+'"' +",\n";    
    print( ret_val + ']\n'+'},\n "ReturnCode": "OK"'+'\n}')

我得到的输出为:

   {
    "Output" :{
     "test_Idlist":[
    "123",
    "456",
    "789",
    "101", # the comma at this point is making json invalid
    ]
    },
     "ReturnCode": "OK"
    }

因此,告诉我在最后一个“ 101”处如何省略逗号。 我尝试使用rstrip,但如果也可以通过其他方式完成操作,那么它也没有起作用,然后plz建议如何使用。 我希望输出为有效的json格式。

我不明白为什么您会尝试使用字符串来构建它。 JSON是一种数据交换格式,在Python数据结构之间来回转换很简单。

您已经在加载输入数据; 您需要做的就是仍然在Python中构建输出数据,然后最后将其转储。

with open("c:/sample.json", 'r') as f:
    data = json.load(f)
ids = [str(item["testid"]) for item in data.values()]
output = {'Output': {'test_Idlist': ids}, 'ReturnCode': 'OK'}
ret_val = json.dumps(output)

您可以跳过循环中的最后一个,然后在循环后添加它,最后不带逗号:

for val in out[:-1]:                   # skip the last one
    ret_val += '"'+val+'"' +",\n";
ret_val += '"'+val+'"' +"\n"           # add the last one without a comma

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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