【问题标题】:Parse code within json (Python)在 json (Python) 中解析代码
【发布时间】:2016-09-10 07:50:03
【问题描述】:

我有以下代码:

from googlefinance import getQuotes
import simplejson as json

print (json.dumps(getQuotes('FRA:BMW'), indent=2))
b=(json.dumps(getQuotes('FRA:BMW'), indent=2))
print(type(b))
a = json.loads((json.dumps(getQuotes('FRA:BMW'), indent=2)))
print(type(a))

这是我得到的:

[
  {
    "LastTradePrice": "73.39",
    "LastTradeWithCurrency": "€73.39",
    "LastTradeDateTime": "2016-05-13T19:57:30Z",
    "LastTradeDateTimeLong": "May 13, 7:57PM GMT+2",
    "ID": "10224532",
    "Index": "FRA",
    "StockSymbol": "BMW",
    "LastTradeTime": "7:57PM GMT+2"
  }
]
<class 'str'>
<class 'list'>
[{'LastTradePrice': '73.39', 'LastTradeWithCurrency': '&#8364;73.39', 'LastTradeDateTimeLong': 'May 13, 7:57PM GMT+2', 'LastTradeDateTime': '2016-05-13T19:57:30Z', 'ID': '10224532', 'Index': 'FRA', 'StockSymbol': 'BMW', 'LastTradeTime': '7:57PM GMT+2'}]
test
Traceback (most recent call last):
  line 11, in <module>
    print((a)["Index"])

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

如您所见,我无法打印“索引”值(在这种情况下:FRA)(脚本的最后一个代码行)不知道它是如何工作的。

【问题讨论】:

  • 您不需要将变量括在括号中。 b=json.dumps(getQuotes('FRA:BMW'), indent=2) 可以工作,但错误提示您无法使用a["index"] 之类的字符串访问列表([data] 的形式)。你可以试试a[0]["Index"]
  • 非常感谢您的支持!

标签: python json string indices


【解决方案1】:

您不需要json 模块来读取该数据。它已经是 Python dictionary。错误说您必须索引getQuotes 返回的列表。由于只有一个元素,所以可以使用[0]

>>> from googlefinance import getQuotes
>>> fra_bmw = getQuotes('FRA:BMW')
>>> fra_bmw[0]["Index"]
u'FRA'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多