0

I wish to save a dictionary and a list in one json file so that when I parse the file I could distinguish them. This is the function I use to save the dictionary in the json file:

def save_callback():
    #folder = filedialog.askdirectory()
    file = filedialog.asksaveasfilename()
    with open(file,'w') as file:
        file.write(json.dumps(test_dict))
    os.rename(file.name,file.name + ".txt")

What should I add to this function to save the list too?

1 Answer 1

1

Since JSON objects can be arbitrarily nested, the easiest solution is to store both the dict and the list inside another object:

data = json.dumps([test_dict, test_list])

Then you can load it like this:

test_dict, test_list = json.loads(data)
Sign up to request clarification or add additional context in comments.

2 Comments

The first part worked but the load returns an error: TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
@evgeny You're not giving it the data, you give it a file. If you wish to give a file, use json.load(file). (Notice the lack of s denoting a string).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.