I'm working with a json file in Python and I wanted to convert it into a dict.
This is what my file looks like:
[
{
"label": "Label",
"path": "/label-path",
"image": "icon.svg",
"subcategories": [
{
"title": "Main Title",
"categories": {
"column1": [
{
"label": "Label Title",
"path": "/Desktop/Folder"
}
]
}
}
]
}
]
So this is what I did:
import json
# Opening JSON file
f = open('file.json')
# returns JSON object as a list
data = json.load(f)
However, data is now a list, not a dict. I tried to think about how can I convert it to a dict, but (I) not sure how to do this; (II) isn't there a way of importing the file already as a dict?
Your data get's imported as list, because in your JSON file the main structure is an Array (squared brackets), which is comparable to a list in Python.
If you want just inner dict you can do
data = json.load(f)[0]
The accepted answer is correct, but for completeness I wanted to offer an example that is increasingly popular for people like me who search for "read json file into dict" and find this answer first (if just for my own reference):
# Open json file and read into dict
with open('/path/to/file.json') as f:
data = json.load(f)
# In the author's example, data will be a list. To get the dict, simply:
data = data[0]
# Then addressing the dict is simple enough
# To print "icon.svg":
print(data.get("image"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With