簡體   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