pythonjsondictionary

How can I import the first and only dict out of a top-level array in a json file?


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?


Solution

  • 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]