提问人:Mahmoud Abdel-Rahman 提问时间:11/12/2023 更新时间:11/12/2023 访问量:42
如何将字符串变量转换为浮点变量JSON文件?
How to convert string variable to float variable JSON file?
问:
我正在尝试从JSON文件中读取字符串并将其转换为浮点数。文件中的其他数据是整数,但此特定数据是字符串。
JSON 文件:
{
"Valuation": {
"TrailingPE": 29.4035,
"ForwardPE": 28.66,
"PriceSalesTTM": 5.5067,
"PriceBookMRQ": 44.6301,
"EnterpriseValue": 2906817822720,
"EnterpriseValueRevenue": 5.9171,
"EnterpriseValueEbitda": 23.52
},"Income_Statement": {
"currency_symbol": "USD",
"quarterly": {
"2023-09-30": {
"date": "2023-09-30",
"filing_date": "2023-11-03",
"currency_symbol": "USD",
"researchDevelopment": "7307000000.00",
"effectOfAccountingCharges": null,
"incomeBeforeTax": "26998000000.00",
"minorityInterest": null,
"netIncome": "22956000000.00",
"sellingGeneralAdministrative": "6151000000.00",
"sellingAndMarketingExpenses": null,
"grossProfit": "40427000000.00",
"reconciledDepreciation": "2653000000.00",
"ebit": "26969000000.00",
"ebitda": "29622000000.00",
"depreciationAndAmortization": "2653000000.00",
"nonOperatingIncomeNetOther": null,
"operatingIncome": "26969000000.00",
"otherOperatingExpenses": "62529000000.00",
"interestExpense": "1002000000.00",
"taxProvision": "4042000000.00",
"interestIncome": "18000000.00",
"netInterestIncome": null,
"extraordinaryItems": null,
"nonRecurring": null,
"otherItems": null,
"incomeTaxExpense": "4042000000.00",
"totalRevenue": "89498000000.00",
"totalOperatingExpenses": "13458000000.00",
"costOfRevenue": "49071000000.00",
"totalOtherIncomeExpenseNet": "29000000.00",
"discontinuedOperations": null,
"netIncomeFromContinuingOps": "22956000000.00",
"netIncomeApplicableToCommonShares": "22956000000.00",
"preferredStockAndOtherAdjustments": null
}
}
法典:
import requests
import json
response = requests.get('some_url')
data = response.json()
# Write JSON File
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# Read JSON File
with open('path_to_file/data.json', 'r') as f:
data = json.load(f)
for statement in data['Income_Statement]['quarterly']['2023-09-30]['netIncome']:
value_ = float(statement)
当我运行上面的代码时,出现以下错误:
ValueError: could not convert string to float: '.'
如何读取此字符串值并将其转换为浮点值并将其放入value_变量中?
*注意:JSON文件在问题中是错误的,但该文件在我的代码中是正确的,并且发布它很大
答:
3赞
Tim Roberts
11/12/2023
#1
您正在做的是逐个字符地遍历该字符串,一次转换一个字符。你在这里不需要循环。只是做for
value = float(data['Income_Statement']['quarterly']['2023-09-30']['netIncome'])
评论