从 Json 文件中提取一个值 (python)

Exctract a value from a Json file(python)

嗨,我不是专家,这个问题让我困扰了很长时间,我希望这里有人能帮助我 我想从以下 json 文件中提取值“interestExpense”:

{'incomeBeforeTax': 17780000000, 
'minorityInterest': 103000000, 
'netIncome': 17937000000, 
'sellingGeneralAdministrative': 5918000000, 
'grossProfit': 16507000000, 
'ebit': 10589000000, 
'endDate': 1640908800, 
'operatingIncome': 10589000000, 
'interestExpense': -1803000000, 
'incomeTaxExpense': -130000000, 
'totalRevenue': 136341000000, 
'totalOperatingExpenses': 125752000000, 
'costOfRevenue': 119834000000, 
'totalOtherIncomeExpenseNet': 7191000000, 
'netIncomeFromContinuingOps': 17910000000, 
'netIncomeApplicableToCommonShares': 17937000000}

在这种情况下,结果应该是 -130000000 作为字符串,但我正在尝试找到一种方法来创建包含所有这些浮点数的列表(或数组),以便我可以决定选择哪个,我没有了解如何操作此类数据(json) 例如

print(list[0])

应该return 17780000000(与incomeBeforeTax相关的值) 这真的可能吗? 输出是从此代码生成的:

annual_is_stms=[]
url_financials ='https://finance.yahoo.com/quote/{}/financials?p{}'
stock= 'F'

response = requests.get(url_financials.format(stock,stock),headers=headers)
soup = BeautifulSoup(response.text,'html.parser')
pattern = re.compile(r'\s--\sData\s--\s')
script_data = soup.find('script',text=pattern).contents[0]

script_data[:500]

script_data[-500:]

start = script_data.find("context")-2
json_data =json.loads(script_data[start:-12])
json_data['context']['dispatcher']['stores']['QuoteSummaryStore'].keys()

#all data relative financials

annual_is=json_data['context']['dispatcher']['stores']['QuoteSummaryStore']['incomeStatementHistory']['incomeStatementHistory']
for s in annual_is:
    statement = {}
    for key, val in s.items():
        try:
            statement[key] = val['raw']
        except TypeError:
            continue
        except KeyError:
            continue
    annual_is_stms.append(statement)
print(annual_is_stms[0])

如果您使用的是python,您需要包含json模块并将其解析为一个对象:

import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

此致

L.

将其复制并粘贴到 Python。

data = {'incomeBeforeTax': 17780000000, 
'minorityInterest': 103000000, 
'netIncome': 17937000000, 
'sellingGeneralAdministrative': 5918000000, 
'grossProfit': 16507000000, 
'ebit': 10589000000, 
'endDate': 1640908800, 
'operatingIncome': 10589000000, 
'interestExpense': -1803000000, 
'incomeTaxExpense': -130000000, 
'totalRevenue': 136341000000, 
'totalOperatingExpenses': 125752000000, 
'costOfRevenue': 119834000000, 
'totalOtherIncomeExpenseNet': 7191000000, 
'netIncomeFromContinuingOps': 17910000000, 
'netIncomeApplicableToCommonShares': 17937000000}

print(data['interestExpense'])

好的,所以您发布的输出片段来自这一行:

print(annual_is_stms[0])

如果您现在想要:-1803000000 您应该这样做:

print(annual_is_stms[0]['interestExpense'])

如果你想要:-130000000你应该这样做:

print(annual_is_stms[0]['incomeTaxExpense'])

如果你想要:17780000000你应该这样做:

print(annual_is_stms[0]['incomeBeforeTax'])