I wrote the code for API using json, but an error occurred.

Asked 2 years ago, Updated 2 years ago, 68 views

I can't find the wrong part myself, but somehow I get an error.
Please let me know who you are.
By the way, this is using the API of the game Crash Royale.

Clash Royale API

The error codes are as follows:

Traceback (most recent call last):
File "C:\Users\mto\Desktop\python_lesson\CRL\crl_api.py", line 53, in <module>
print(battle_info()[0]["type"])
TypeError: string indications must be integrers

Actual Code

import json
import requests

access_key=# omitted here

URL='https://api.clashroyale.com/v1'

def battle_info():
    target_api=URL+"/players/"
    playerTag="%238QRCJQ9Y"
    url=target_api+playerTag+"/battlelog"
    headers = {
        "content-type": "application/json; charset=utf-8",
        "cache-control": "max-age=60",
        "authorization": "Bearer%s" %access_key}
    r=requests.get(url,headers=headers)
    data=r.json()
    result=json.dumps(data,indent=4) 
    return result

print(battle_info()[0]["type"])

Also, if you output the following battery_info(), you will see the following

#execution code
print(battle_info())
# result of execution result
[
    {
        "type": "challenge",
        "battleTime": "20190509T081821.000Z"

    # Omit the continuation

python python3 json api

2022-09-30 16:54

1 Answers

In your current code, you have decoded the response you have obtained in the API with r.json() and converted it into Python's List, Dictionary (data) into a string with dump.

So it's like doing this.

jsonText='\
[
    {
        "type": "challenge",
        "battleTime": "20190509T081821.000Z"
        ...
'''
print(jsonText[0]["type"])

jsonText[0] returns the first single character '[' as a string, so you are trying to reference an index called ["type"] for that string, so TypeError:string indications must be integers is an error.

You may want to return data as the return value for battle_info().

def battle_info():
    target_api=URL+"/players/"
    playerTag="%238QRCJQ9Y"
    url=target_api+playerTag+"/battlelog"
    headers = {
        "content-type": "application/json; charset=utf-8",
        "cache-control": "max-age=60",
        "authorization": "Bearer%s" %access_key}
    r=requests.get(url,headers=headers)
    data=r.json()
    return data

Try it.


2022-09-30 16:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.