1

So I'm trying to learn more about APIs and the different ways I can use them. Say that as of right now I have

import requests, json, pprint

r = requests.get("values from api") 

pprint.pprint(r.json())

which returns to me the following

> {'currentResultCount': '10',  
> 'results': [{'Name': 'Item_One',
>               'Price': '464086'},
>              {'Name': 'Item_Two',
>               'Price': '70874',
>                and so on.........

If I want to store all the price in an array and do some data analysis on them (like find the mean, median, and mode), what should I do?

I tried calling r[0] to see if it's functional or not, but apparantly r is an response object type, so r[0] doesn't work. This is my first time learning about API and data manipulation, any suggestions and learning tips are greatly appreciated!

user3277633
  • 1,891
  • 6
  • 28
  • 48

2 Answers2

4

.json() parses JSON response under the hood and returns you a Python data structure, in your case, a regular dictionary:

data = r.json()

To get the list of prices, iterate over the results values and get the Price on every iteration:

prices = [item['Price'] for item in data['results']]

You may also cast prices to float:

prices = [float(item['Price']) for item in data['results']]
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I am using `res = conn.getresponse() data = res.read() print(data.decode("utf-8")) mydata = data.json()` But what I get is, `RemoteDisconnected: Remote end closed connection without response` What should be done ? – Sarang Manjrekar Jan 31 '17 at 09:55
1

Here r is Response type object which contains a server's response to an HTTP request. Now in your code you are using,

r = requests.get("values from api")

get method must receive a url as parameter.

You can use dir(r) to see the properties of the object. You can try some of them. If there is a json-encoded content of a response, r.json() will return it. Now json is very much similar to python dictionary. So you can use this as a dictionary, store it in a list and also manipulate the data.

Nathan Basanese
  • 8,475
  • 10
  • 37
  • 66
salmanwahed
  • 9,450
  • 7
  • 32
  • 55