Json file gets load as list instead of dict. using python

Viewed 2844

I am trying to learn to get information from a json file. The json file which in 250MB is size is on my desktop.

I am new to python and I am certain that I am missing something in spite of the tireless google to get an answer.

my understand while i load a Json file, the expected type is to be a Dict.

import json

with open (r'c:\eseek\limitsdata.json) as f:
   data = json.load(f)

print type(data)

I get <class 'list'> as the output... but not sure why this is not a dict as I see in many tutorials

I just realized that this is similar to already available post [https://stackoverflow.com/questions/57030807/python-json-loads-returns-list-instead-of-dict]

I wanted to iterate to the json, but as i try the following steps ... it does not work

data_str = json.dumps(data)
print(data_str[0])

I dont get the first nested group, but i get the first string "["

I know I am missing something here. it will be great if someone can highlight the same

Sample data. I am trying to the task details if the model is 500 in the master file.

[
    {
        "Model": " 500",
        "Task": “71-00-00-200-802 ",

    },
    {
        "Model": " 900",
        "Task": " 71-00-00-200-802",

    }
]
1 Answers

If the first character is "[" then the json file should indeed be parsed as a list. For example,

a_list = json.loads("[ 'a', 'b', 'c' ] ")   # should give list [a,b,c]
a_dict = json.loads("{ 'data' : ['a', 'b', 'c']} ") # gives a dict

print(type(a_list), type(a_dict)) # should be list, dict
a_dict['data']  # can look up the field in this dict

As for your second issue: if you want to iterate over items (first item of a_list above is the item "a") then keep it as a list. If you want to iterate over characters (the first character of json.dumps(a_list) is "["), then you convert it to a string first.

You do not need to convert the json back to a string to iterate over it, and can just do

for item in a_list:
    print(item)

Edit: For your data in particular, you can access fields as follows:

with open (r'c:\eseek\limitsdata.json') as f:
   data = json.load(f)

print( data[0]["Model"] ) # prints '500'
print( data[1]["Task"] ) # prints ' 71-00-00-200-802'
Related