edmamerto
edmamerto

Reputation: 8165

Python requests accessing index of response object

I'm new to python and trying to practice aggregating data from an api call

i have this script

r = requests.get('https://jsonplaceholder.typicode.com/users')

print r.text

which returns an array of objects in this format

  [{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
   }]

I've been playing around and tried this to see if I can access the first object

print r.text[0]

And it didn't work. So how do I do this with python

Upvotes: 0

Views: 3082

Answers (2)

devkingsejong
devkingsejong

Reputation: 76

request.text returns Http response body. so If you want to get first propery of json,
you should convert string to json object.

This works

result = r.text
print(type) # prints str

import json
result = json.loads(result)

print(result[0]) # (...)

Upvotes: 1

Barmar
Barmar

Reputation: 782158

You need to parse the JSON text:

import json
array = json.loads(r)
print array[0]

Upvotes: 2

Related Questions