简体   繁体   English

如何将 json 作为字典导入?

[英]How can I import a json as a dict?

I'm working with a json file in Python and I wanted to convert it into a dict.我正在处理 Python 中的 json 文件,我想将其转换为字典。

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? (II) 没有办法将文件作为字典导入吗?

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.您的数据作为列表导入,因为在您的 JSON 文件中,主要结构是一个数组(方括号),它与 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM