How can I import a json as a dict?
Question:
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"
}
]
}
}
]
}
]
(sorry about the identation)
So this is what I did:
import json
# Opening JSON file
f = open('file.json')
# returns JSON object as
# a dictionary
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?
Answers:
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]
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))
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"
}
]
}
}
]
}
]
(sorry about the identation)
So this is what I did:
import json
# Opening JSON file
f = open('file.json')
# returns JSON object as
# a dictionary
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]
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))