json dump generating unnecessary curly braces

时间:2017-08-04 12:19:06

标签: python python-2.7 dictionary

This question might have been asked many times but I am still unable to understand how to use json file. I use json.dump(data, filename). While dumping I get unnecessary {} at the end of the file. So json.load(data) gives me below error.

simplejson.scanner.JSONDecodeError: Extra data: line 1 column 1865 - line 1 column 1867 (char 1864 - 1866)

I read that there is no way to load a first or second dictionary. I have also read that there is a separater which can be used with json dump but I see no use here. Should I be using encoding, decoding here?

My json.dump file:

    {
    "deployCI2": ["094fd196-20f0-4e8d-b946-f74a56d2f319", "6a1ce382-98c6-4058-a929-95a7d2415fd0"], 
    "deployCI3": ["c8fff661-4482-4908-b722-4fac0227a8b0", "929cf1fa-3fa6-4f95-8464-d58e5490f4cf"],  
    "deployCI4": ["9f8ffa3c-460d-43a9-8113-58e891340e1b", "6e535e92-4da2-4228-a6ab-c8fc8d31adcd", "8e26a35e-7fb9-43b3-8026-d1283f7b678c", "f40e5c29-b4df-4cfb-9d7f-3bcc9c4dcf9f"], 
    "HeenaStackABC": [], "HeenaStackABC-DISK_VM1-mm55lkkvccej": ["cc2a89a2-3b27-4f88-af09-b3b0b1301056"]
    }{}

Edited: I think the code is doing something here.

with open('stackList.json', 'a') as f:
    for stack in stacks:
        try:
            hlist = hc.resources.list(stack_id=stack.id)
            vlist = [o.physical_resource_id for o in hlist if o.resource_type =='OS::Cinder::Volume']
            myDict[stack.stack_name] = vlist
        except heatclient.exc.HTTPBadRequest as e:
            pass
    json.dump(myDict,f)

I edited the code like below. I hope this is valid. It removed the last braces

    if len(myDict) != 0:
       json.dump(myDict, f)

1 个答案:

答案 0 :(得分:1)

Your problem is here :

with open('stackList.json', 'a') as f:

You're opening the file in 'append' mode, so each time the code is executed it appends the dump to your file. The result you complain about comes from this and mydict being empty on the second run.

You either have to open the file in "w" ("write") mode which will overwrite the existing content (you can eventually create a new dump file for each call) or switch to the "jsonline" format (but your file will NOT be a valid json file anymore and any code reading it will have to know to parse it as jsonlines)