I am trying to pass in a JSON file and convert the data into a dictionary.
So far, this is what I have done:
import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
I'm expecting json1_data
to be a dict
type but it actually comes out as a list
type when I check it with type(json1_data)
.
What am I missing? I need this to be a dictionary so I can access one of the keys.
Here is a simple snippet that read's in a
json
text file from a dictionary. Note that your json file must follow the json standard, so it has to have"
double quotes rather then'
single quotes.Your JSON dump.txt File:
Python Script:
Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:
Now you can access the data stored in datapoints just as you were expecting:
datapoints[0:5][0]
doesn't do what you're expecting.datapoints[0:5]
returns a new list slice containing just the first 5 elements, and then adding[0]
on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:Here's a simple way to calculate the mean:
If you're willing to install NumPy, then it's even easier:
Using the
,
operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.
Below is the sample snippet that can be used.