如何在python中从这个json获取值?

时间:2017-04-29 07:54:59

标签: python json django

我目前正在使用python并从API获取一些json响应。 但在尝试从json获取数据后,我总是收到此错误, TypeError:字符串索引必须是整数,而不是str 这是我收到的JSON文件,

{
  "from": 1,
  "to": 10,
  "currentPage": 1,
  "total": 72,
  "totalPages": 8,
  "queryTime": "0.023",
  "totalTime": "0.059",
  "partial": false,
  "canonicalUrl": "/v1/products(categoryPath.name=All Flat-Panel TVs)?show=sku,name,salePrice&format=json&apiKey=APIKEY",
  "products": [{
    "sku": 3813048,
    "name": "Samsung - 32\" Class (31-1/2\" Diag.) - LED - 1080p - HDTV - Black",
    "salePrice": 229.99
  }, {
    "sku": 4340402,
    "name": "Samsung - 43\" Class (42.5\" Diag.) - LED - 1080p - Smart - HDTV - Black",
    "salePrice": 429.99
  }, {
    "sku": 4380083,
    "name": "Samsung - 32\" Class (31.5\" Diag.) - LED - 1080p - Smart - HDTV - Silver",
    "salePrice": 299.99
  }, {
    "sku": 4405201,
    "name": "Samsung - 50\" Class (49.5\" Diag.) - LED - 1080p - Smart - HDTV - Black",
    "salePrice": 499.99
  }, {
    "sku": 4559300,
    "name": "VIZIO - 39\" Class (38.5\" Diag.) - LED - 720p - Smart - HDTV - Black",
    "salePrice": 269.99
  }, {
    "sku": 4562031,
    "name": "Samsung - 58\" Class (57.5\" Diag.) - LED - 1080p - Smart - HDTV - Black",
    "salePrice": 649.99
  }, {
    "sku": 4569901,
    "name": "LG - 24\" Class (23.6\" Diag.) - LED - 720p - HDTV - Black",
    "salePrice": 84.99
  }, {
    "sku": 4613600,
    "name": "Samsung - 32\" Class (31.5\" Diag.) - LED - 720p - Smart - HDTV - Black",
    "salePrice": 219.99
  }, {
    "sku": 4629257,
    "name": "Samsung - 32\" Class (31.5\" Diag.) - LED - 720p - HDTV - Black",
    "salePrice": 199.99
  }, {
    "sku": 4673800,
    "name": "Insignia™ - 24\" Class (23.6\" Diag.) - LED -720p - Smart - Roku TV - Black",
    "salePrice": 139.99
  }]
}

我试过以下方式,

for item in result["products"]:
    print(item["sku"])
    print(item["name"])
    print(item["salePrice"])

for item in result:
    print(item["products"]["sku"])
    print(item["products"]["name"])
    print(item["products"]["salePrice"])

任何人都可以告诉我,我错了吗?你可以分享一些教程,我可以理解如何正确解码json。 提前谢谢

1 个答案:

答案 0 :(得分:2)

你必须缺少解析这个json。首先解析它,然后像你一样做。

import json
results = json.loads(results)
for item in results['products']:
    print(item["sku"])