Reputation: 314
I am currently working in python and getting some json response from API. but after trying my best to fetch data from json, I am always getting this error, TypeError: string indices must be integers, not str here is my JSON file that I received,
{
"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
}]
}
and I have tried in following ways,
for item in result["products"]:
print(item["sku"])
print(item["name"])
print(item["salePrice"])
and
for item in result:
print(item["products"]["sku"])
print(item["products"]["name"])
print(item["products"]["salePrice"])
Can anyone tell me please where I am wrong? Can you please share some tutorials where I can understand how to decode json properly. thanks in advance
Upvotes: 0
Views: 99
Reputation: 22875
You must be missing to parse this json. Parse it first and then do as you are doing.
import json
results = json.loads(results)
for item in results['products']:
print(item["sku"])
Upvotes: 2