简体   繁体   中英

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

I have a sample.json file as follows:

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

I have to fetch the testid of each test section and get it in a following from:

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

I did the following script:

   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}')

and i get th output as :

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

So, tell me how do i ommit comma at the last enrty"101". I tried using rstrip but it didnt worked also if the same can be done in other way then plz suggest how. I want the output to be in valid json format.

I don't understand why you would try and build this up using strings. JSON is a data interchange format, and it is trivial to convert it to and from Python data structures.

You are already loading your input data; all you need to do is to build up your output data still in Python, then dump it at the end.

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)

You can skip the last one in your loop and add it after the loop without a comma at the end:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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