I am not sure that I have got this right; I am trying to use json library in python.
I dump a nested dictionary in a json file on disk, and then I would like to load it back as it was before. Although when I load back the file, I don't get the same object that I had before.
mydictionary=defaultdict(dict)
...
with open("myfile.json", "w") as outfile:
dump(mydictionary, outfile) #saving the dictionary to json file
....
with open("myfile.json") as outfile:
restored_dict=load(outfile)
for keys in restored_dict:
print keys
The dictionary structure:
{
"product1": {
"item1" : [
"red",
"soft",
"430"
],
"item2" : [
"green",
"soft",
"112"
],
"item3" : [
"blue",
"hard",
"12"
]
},
"product2": {
"item4" : [
"black",
"soft",
"30"
],
"item5" : [
"indigo",
"hard",
"40"
],
"item6" : [
"green",
"soft",
"112"
]
}
}
When I print the object before and after, they are not the same; I cannot access the keys and values anymore, once I restore the dictionary. I get a long sequence of data, with a "u" at the beginning of each item and key; the only way to print it correctly is if I dump it again and print the output
print dumps(restored_dict, indent=4)
But I still cannot access the keys, values and items.
I see that there are 2 functions: one has the s at the end (dump-dumps, load-loads), but I can't tell the difference. Some tutorials online say that the one with the s is creating a string instead than a json object, while others say that one save in binary and another in plain text...
I am trying to save the dictionary, and load it at later time; I thought that json was the simplest way to achieve this, but for some reason I can't achieve this.