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!

2
  • you are already doing it by r.json() Commented Sep 19, 2014 at 22:13
  • sorry but I havn't really looked into what exactly json is yet, but it does seem like json will answer my question. Thanks for the tip! Commented Sep 19, 2014 at 22:15

2 Answers 2

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']]
Sign up to request clarification or add additional context in comments.

1 Comment

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 ?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.