字符串索引必须是整数,而通过JSON解析

发布于 2025-02-07 08:45:20 字数 2316 浏览 2 评论 0原文

因此,我试图抓住“ rate_float”,但是每当通过响应运行时,我都会得到TypeError。

我很确定,当试图通过“ BPI”

我最初认为这是因为包含在字符串中,但它是浮点,这仍然是造成问题,或者我不正确解析JSON以获取“ USD”,并获得“ rate_float”的值

对美元。

错误消息:

    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

完整的代码:

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
    }
  }
}

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": "$",
      "rate": "27,091.6395",
      "description": "United States Dollar",
      "rate_float": 27091.6395
    },
    "GBP": {
      "code": "GBP",
      "symbol": "£",
      "rate": "21,996.2168",
      "description": "British Pound Sterling",
      "rate_float": 21996.2168
    },
    "EUR": {
      "code": "EUR",
      "symbol": "€",
      "rate": "25,752.4997",
      "description": "Euro",
      "rate_float": 25752.4997
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2025-02-14 08:45:20

问题在这里,

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

当您迭代字典时,您会迭代其键。这样,p是字符串(例如usdgbp etc)。

考虑使用items()对密钥和值进行迭代:

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

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"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文