Reputation: 989
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?
Upvotes: 18
Views: 37639
Reputation: 61
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"))
Upvotes: 1
Reputation: 578
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]
Upvotes: 18
Reputation: 51
I'm not too sure, but I would think, in a dictionary, you would need a key and a value, so in this example, i'm creating a list for labels/images and then creating a dictionary.
# ***** Create List *****
list_label=[]
list_image=[]
# ***** Iterate Json *****
for i in data:
list_label.append(str(i['label']))
list_image.append(i['image'])
# ***** Create Dictionary *****
contents = dict(zip(list_label, list_images))
Upvotes: -2