Skip to content
Advertisement

Exctract a value from a Json file(python)

Hi i’m not an expert and this problem kept me stuck for such a long time I hope that someone here can help me i would like to exctract the value “interestExpense” from the following json file:

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

In this case the result should be -130000000 as a string but i m trying to find a way to create an list(or an array) with all those floats so that i can decide which one to pick, i have no idea how to manipulate this kind of data(json) For example

print(list[0])

should return 17780000000(the value associated with incomeBeforeTax) is this actually possible? The output is generated from this code:

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--sDatas--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])

Advertisement

Answer

If you are using python, you need to include the json module and parse it as an object:

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"])

Regards

L.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement