I get an error while trying to read this dictionary - python

I get this api response from coinbase
json_response = {"ask":"19540.18","bid":"19538.23","volume":"46199.99613583","trade_id":420452773,"price":"19539.07","size":"0.00091338","time":"2022-09-28T16:44:27.381482Z"}
and when i try to get the "ask" data by using
print(json_response["ask"])
i get the error
Traceback (most recent call last):
print(json_response["ask"])
TypeError: string indices must be integers
I read on W3schools and this works for them.
Thanks in advance

The error message is leading you towards the right approach:
String indices must be integers
i.e, you are trying to index into a string, not a dictionary as you think. One way to approach this is by parsing the response string into a dictionary first:
import json
data = json.loads(json_response)
print(Type(data))
print(Type(json_response))
print(data['ask']) #should get you the expected result

Your API response is being stored in a dictionary of lists, instead of a pure dictionary itself.
(For examples on what this looks like, go here:
https://www.geeksforgeeks.org/python-ways-to-create-a-dictionary-of-lists/)
Hence the reason you are getting the error is because json_response can only be accessed using indices.
You need to convert your list of items into a dictionary first.
One way to do that:
json_response = {"ask":"19540.18","bid":"19538.23","volume":"46199.99613583","trade_id":420452773,"price":"19539.07","size":"0.00091338","time":"2022-09-28T16:44:27.381482Z"}
json_response_dict = dict()
for key in json_response:
json_response_dict[key] = json_response[key]
Then this code will appropriately convert the list into a useable dictionary and the following code:
print(json_response_dict)
print(json_response_dict["ask"])
Will work and print:
{'ask': '19540.18', 'bid': '19538.23', 'volume': '46199.99613583', 'trade_id': 420452773, 'price': '19539.07', 'size': '0.00091338', 'time': '2022-09-28T16:44:27.381482Z'}
19540.18

Related

Why is an expression like ['a']['b'] an error instead of getting values from a nested dict?

I am trying to get the subscriber count from a youtube channel using the youtube api. However the repsonse sends a nested dict with more information than just the subscriber count. Here is the code I tried using to solve the problem
from googleapiclient.discovery import build
api_key = 'my_key'
youtube = build('youtube', 'v3', developerKey=api_key)
request = youtube.channels().list(
part='statistics',
forUsername='pewdiepie'
)
response = dict(request.execute())
print(response)
print(['items']['statistics'])
However I come up with this error
list indices must be integers or slices, not str
Here is the response I get from the youtube api
{'kind': 'youtube#channelListResponse', 'etag': 'b1tpsekLNgax8TyB0hih1FujSL4', 'pageInfo': {'totalResults': 1, 'resultsPerPage': 5}, 'items': [{'kind': 'youtube#channel', 'etag': 'gdAP8rVq0n-1Bj2eyjvac-CrtdQ', 'id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw', 'statistics': {'viewCount': '28147953019', 'subscriberCount': '111000000', 'hiddenSubscriberCount': False, 'videoCount': '4459'}}]}
Change the last line in your code to:
for item in response['items']:
print(item['statistics'])
Based on the response you are posting here, if you want to know statistics from an item, you have to specify from which item you are trying to get statistics. items is a list, which means that you have to refer to it's elements by numerical index. It has a length as well, you can get by using len(response['items']). Now, let's say you want to get the subscriberCount from the first item in the list, in that case you can retrieve it with the following code:
if (len(response['items']) > 0):
response['items'][0]['statistics']['subscriberCount']
In order to access a value in a dictionary you actually have to include the dictionary in the expression.
['items']['statistics'] alone creates a list containing one string, 'items', and tries to access that list using the string 'statistics' as index. But this is bad, because list indices must be integers.
In order to access the key 'items' in the dictionary response, you can use response['items'].
Assuming this returns another, nested, dictionary, you can then access the key 'statistics' in that dictionary by using response['items']['statistics'].

Extract value from json data using python

After doing an API request I get the json 'data' this has each record in a different set if curly brackets under the results square brackets.
I want to extract the numbers and store/print them separated with a comma.
so requested output
0010041,0010042
I have tried using the below however it comes back with the following error.
TypeError: list indices must be integers or slices, not str
If the results only has one set of brackets it works fine, do I have to convert the multiple results into one so and then extract all the times when 'number' appears?
import json
import sys
#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
print (resp['result'])
print (resp['result']['number'])
Error message is clear: you are trying to access a list of dicts and you aren't doing it correctly.
Replace your last line with:
for i in resp['result']:
print(i['number'])
Update:
As suggested in comments, you can use list comprehension. So to get your desired result, you can do:
print(",".join([i['number'] for i in resp['result']]))

TypeError: string indices must be integers when using string split to pass paramerters to a json api

This the main drive Im using to call the call the functions from the mentioned call.
from primeReportController import PrimeReportController
input_str = input()
a = input_str.split(",",1)
report_date,report_name = a[0],a[1]
prime = PrimeReportController()
prime.generatePrimeReport(report_date,report_name)
This is the call function definition writhing the class
Also please note the function adds the json data to a sql database. The data is already formatted to fit the table schema.
Since the output of response.json() is {'message': 'The request is invalid.'}, it tells you that your request is invalid to the server, and that the returning value would not have the data structure you expected. So when you iterate over the response dict with:
for x in server_response:
What it really does is to iterate over the keys of the dict {'message': 'The request is invalid.'}, x becomes 'message' in the first iteration, so when you try to get the value of x['cell'], it consequently complains about your trying to access a string with a non-integer index.
You simply have to fix the request you send to the server first.

Extracting data using python from the steam api formatted in JSON

I want to get the name and percent data from the json string...
{'achievementpercentages': {'achievements': [{'name': 'camp_bonus_01_stalingrad_rail_german_engineering', 'percent': 42}, {'name': 'count_camp_1', 'percent': 41.5}
Ive been trying to do this using something like...
for achievementpercentages in repos:
print(achievementpercentages['name'])
print(achievementpercentages['percent'])
but this returns the error...
TypeError: string indices must be integers
That's not a valid json string but that doesn't mean you can't use it. The issue you're having is explained by the error. Your loop isn't saying what you want to do based on the structure of your dictionary. If your repo variable is filled with a list of many rows(dicts) that look like your example line then your code needs to be:
for row in repo:
for achievement in row['achievementpercentages']['achievements']:
print achievement['name']
print achievement['percent']
It's a little unclear what repos is... if repos is your entire string you pasted it needs to be:
for achievemnt in repo['achievementpercentages']['achievements']:
print achievement['name']
print achievement['percent']`

TypeError: list indices must be integers or slices, not str while parsing JSON

I am trying to print out at least one key value from the returned Json, as following this basic tutorial
response=None
booking_source = 'sourceBusinessName'
api_request ='http://api.com'
r = requests.get(api_request)
while response is None:
response = r.content.decode('utf-8')
data = json.loads(response)
print (data[booking_source])
return HttpResponse(data[booking_source])
But it returns TypeError: list indices must be integers or slices, not str
probably because I am giving an string instead of an integer to data when printing, but then what I am doing wrong here ?
With requests you can skip the decoding of the response and parsing it as JSON by using the response's json method:
r = requests.get(api_request)
data = r.json()
print data # so you can see what you're dealing with
At this point I suggest dumping out the value of data so that you can see the structure of the JSON data. Probably it is a JSON array (converted to a Python list) and you simply need to take the first element of that array before accessing the dictionary, but it's difficult to tell without seeing the actual data. You might like to add a sample of the data to your question.
Your JSON is an array at the top level, but you're trying to address it as if it were:
{
"sourceBusinessName": {
...
},
...
}

Categories

Resources