我有一个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"
}
所以,请告诉我如何在最后的enrty" 101"中省略逗号。我尝试使用rstrip但它也没有用,如果可以用其他方式完成相同,那么plz建议如何。我希望输出是有效的json格式。
答案 0 :(得分:1)
我不明白为什么你会尝试使用字符串来构建它。 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)
答案 1 :(得分:0)
你可以跳过循环中的最后一个并在循环之后添加它而不用逗号结尾:
for val in out[:-1]: # skip the last one
ret_val += '"'+val+'"' +",\n";
ret_val += '"'+val+'"' +"\n" # add the last one without a comma