Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 319
dekio Avatar asked Dec 05 '25 13:12

dekio


2 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]
like image 101
Александр Свито Avatar answered Dec 07 '25 12:12

Александр Свито


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"))
like image 41
Ryan Avatar answered Dec 07 '25 11:12

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!