首页 > 解决方案 > Python请求访问响应对象的索引

问题描述

我是 python 新手,正在尝试从 api 调用中聚合数据

我有这个脚本

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

print r.text

它以这种格式返回一个对象数组

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

我一直在玩,并尝试了这个,看看我是否可以访问第一个对象

print r.text[0]

它没有用。那么我该如何用python做到这一点

标签: python

解决方案


您需要解析 JSON 文本:

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

推荐阅读