[英]How do I pull out a certain segment from a string
我正在使用给我的 API 和 output 格式为
['{"quote":{"symbol":"AAPL"', '"companyName":"Apple Inc."', '"primaryExchange":"Nasdaq Global Select"', '"sector":"Technology"', '"calculationPrice":"close"', '"open":367.88', '"openTime":1593696600532', '"close":364.11', '"closeTime":1593720000277', '"high":370.47', '"low":363.64', '"latestPrice":364.11'}]
...(它继续像这样,有更多的类别。)
我试图只提取最新价格。 最好的方法是什么?
这就是我所拥有的,但我得到了一堆错误。
string = (data.decode("utf-8"))
data_v = string.split(',')
for word in data_v[latestPrice]:
if word == ["latestPrice"]:
print(word)
print(data_v)
从 output 判断,这是 JSON。 To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).
如果我是正确的,您从 Yahoo Finance 获得了此 output,如果确实如此,请不要手动获取和解析它,而是使用 yfinance 模块(请参阅https://pypi.org/project/yfinance/ )
您必须使用JSON
模块来解析此JSON
字符串。 你可以把它转换成字典。 为了便于理解,我缩进了 JSON 代码。 您可以使用以下方法,
import json
text_to_parse = """
{"quote":
{
"symbol":"AAPL",
"companyName":"Apple Inc.",
"primaryExchange":"Nasdaq Global Select",
"sector":"Technology",
"calculationPrice":"close",
"open":367.88,
"openTime":1593696600532,
"close":364.11,
"closeTime":1593720000277,
"high":370.47,
"low":363.64,
"latestPrice":364.11
}
}
"""
parsed_dict = json.loads(text_to_parse)
print(parsed_dict["quote"]["latestPrice"])
程序运行时输出364.11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.