I’m relatively new to working with JSON and am trying to output a dictionary to JSON using the json library in python. The issue I have is the format is very specific and I’m not sure how to approach. Specifically the desired format has extra braces and brackets. Below is an example of the dictionary I’m converting to JSON and the desired output:
#Sample Data
sample_dict = {"office":{"50":"pencil;paper",
"100":"stapler;eraser"},
"warehouse":{"50":"forklift;wrench",
"100":"truck,screw"}}
with open('test.json', 'w') as f:
json.dump(sample_dict, f,indent = 4)
##Output I'm able to acheive
{
"office": {
"50": "pencil;paper",
"100": "stapler;eraser"
},
"warehouse": {
"50": "forklift;wrench",
"100": "truck,screw"
}
}
##Desired Output
[{
{"office": {
"50": "pencil;paper",
"100": "stapler;eraser"
}},
{"warehouse": {
"50": "forklift;wrench",
"100": "truck,screw"
}}
}]
2
Answers
I think you need to make the “sample_dict” a string with square brackets.
The extra
[]
would be easy — the whole dictionary is in a list. However, the extra{}
are not; the sample you posted is not, in fact, valid JSON.At this point, you’ll need to clarify whether the output should be JSON or whether it should match the given sample.
If the output should be JSON, you’ll need to get a correct sample output, then work from there. At a minimum, the top level is a list of dictionaries.
If the output should match the given sample, it’s not JSON and you won’t be using the
json
library. Depending on the situation, you can:%
or.format()
orf"..."
strings); or