Home > Blockchain >  String indices must be integers, while parsing through json
String indices must be integers, while parsing through json

Time:06-13

So, I am trying to grab the "rate_float", but whenever running through the response I get the TypeError.

I am pretty sure I the TypeError is actually happening right off the bat whenever trying to loop through "bpi"

I originally thought it was because contained in a string but it's a float, is that still what is causing the issue, or is that im not parsing the json correctly to get to "USD", and get the value pair of "rate_float"

Correct code should just output the rate_float of USD.

Error Message:

    Traceback (most recent call last):
  File "C:\Users\Blue\python_practice\problem_sets\Bitcoin_Price", line 37, in <module>
    main()
  File "C:\Users\Blue\python_practice\problem_sets\Bitcoin_Price", line 7, in main
    bitcoin_price = bitcoin()
  File "C:\Users\Blue\python_practice\problem_sets\Bitcoin_Price", line 34, in bitcoin
    print(p["rate_float"])
TypeError: string indices must be integers

Full set of code:

import requests
import json
import sys


def main():
    bitcoin_price = bitcoin()
    print(bitcoin_price)
    try:
        if float(args()):
            print(args())
            return True
    except ValueError:
        print("Invalid Amount / Not a float or digit")
        sys.exit()


def args():
    arg = [float(x) for x in sys.argv[1:]]
    user_arg = arg.pop(0)
    return user_arg


def bitcoin():
    response = requests.get(
        "https://api.coindesk.com/v1/bpi/currentprice.json")

    print(json.dumps(response.json(), indent=2))

    usd_price = response.json()

    for p in usd_price["bpi"]:
        print(p["rate_float"])


main()

json:

    {
  "time": {
    "updated": "Jun 12, 2022 23:29:00 UTC",
    "updatedISO": "2022-06-12T23:29:00 00:00",
    "updateduk": "Jun 13, 2022 at 00:29 BST"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "chartName": "Bitcoin",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "&#36;",
      "rate": "27,091.6395",
      "description": "United States Dollar",
      "rate_float": 27091.6395
    },
    "GBP": {
      "code": "GBP",
      "symbol": "&pound;",
      "rate": "21,996.2168",
      "description": "British Pound Sterling",
      "rate_float": 21996.2168
    },
    "EUR": {
      "code": "EUR",
      "symbol": "&euro;",
      "rate": "25,752.4997",
      "description": "Euro",
      "rate_float": 25752.4997
    }
  }
}

CodePudding user response:

The problem is here

for p in usd_price["bpi"]:
    print(p["rate_float"])

When you iterate over a dictionary, you iterate over its keys. That way, p is a string (e.g. USD, GBP etc).

Consider iterating over the key and values using items():

for currency, val in usd_price["bpi"].items():
    print(currency, val["rate_float"])
  • Related