[英]How do I pull out a certain segment from a string
I'm using an API that is giving me and output formatted as我正在使用给我的 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'}]
...(it keeps going like this with many more categories.) ...(它继续像这样,有更多的类别。)
I am attempting to pull out only the latest price.我试图只提取最新价格。 What would be the best way to do that?最好的方法是什么?
This is what I have but I get a bunch of errors.这就是我所拥有的,但我得到了一堆错误。
string = (data.decode("utf-8"))
data_v = string.split(',')
for word in data_v[latestPrice]:
if word == ["latestPrice"]:
print(word)
print(data_v)
Judging by the output this is JSON.从 output 判断,这是 JSON。 To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ). To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).
If I'm correct you got this output from Yahoo Finance, if this indeed the case don't fetch and parse it manually but use the yfinance module (see https://pypi.org/project/yfinance/ )如果我是正确的,您从 Yahoo Finance 获得了此 output,如果确实如此,请不要手动获取和解析它,而是使用 yfinance 模块(请参阅https://pypi.org/project/yfinance/ )
You will have to use JSON
module to parse this JSON
string.您必须使用JSON
模块来解析此JSON
字符串。 You can convert it into dictionary then.你可以把它转换成字典。 I have indented the JSON code for ease of understanding.为了便于理解,我缩进了 JSON 代码。 You can use the following approach,您可以使用以下方法,
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"])
When the program is run, it outputs 364.11
程序运行时输出364.11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.