Your JSON is an array with one object inside, so when you read it, you get a list with a dictionary inside. You can access your dictionary by accessing element 0 in the list, as shown below:
json1_data = json.loads(json1_str)[0]
Now you can access the data stored in datapoints, as expected:
datapoints = json1_data['datapoints']
I have another question if someone can bite: I'm trying to take the average of the first elements at these data points (that is, datapoints [0] [0]). Just to list them, I tried to execute datapoints [0: 5] [0], but all I get is the first datapoint with both elements, and not the desire to get the first 5 data containing only the first element. Is there any way to do this?
datapoints[0:5][0] does not do what you expect. datapoints[0:5] returns a new slice of the list containing only the first 5 elements, and then adding [0] at the end of this will only accept the first element from this resulting list. To get the desired result, you need to remember the list :
[p[0] for p in datapoints[0:5]]
Here's a simple way to calculate the average:
sum(p[0] for p in datapoints[0:5])/5.
If you want to install NumPy , then this is even simpler:
import numpy json1_file = open('json1') json1_str = json1_file.read() json1_data = json.loads(json1_str)[0] datapoints = numpy.array(json1_data['datapoints']) avg = datapoints[0:5,0].mean()
Using a statement with slice syntax for NumPy arrays has the behavior you originally expected with lists.
DaoWen Oct 20 '13 at 22:05 2013-10-20 22:05
source share