亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將帶有浮點數的json字符串解析為python中的字符串

將帶有浮點數的json字符串解析為python中的字符串

慕斯709654 2022-06-14 16:56:09
我正在編寫一個使用 python 請求從 URL 讀取 json 的類對象。json 字符串很奇怪,因為浮點數、日期和整數都是字符串。{"financialStatementList" : [ {"symbol" : "HUBS","financials" : [ {  "date" : "2018-12-31",  "Revenue" : "512980000.0",  "Revenue Growth" : "0.3657",  "Cost of Revenue" : "100357000.0",  "Gross Profit" : "412623000.0",  "R&D Expenses" : "117603000.0",  "SG&A Expense" : "343278000.0",  "Operating Expenses" : "460881000.0",  "Operating Income" : "-48258000.0",  "Interest Expense" : "21386000.0",  "Earnings before Tax" : "-61960000.0",  "Income Tax Expense" : "1868000.0",  "Net Income - Non-Controlling int" : "0.0",  "Net Income - Discontinued ops" : "0.0",  "Net Income" : "-63828000.0",  "Preferred Dividends" : "0.0",  "Net Income Com" : "-63828000.0",  "EPS" : "-1.66",  "EPS Diluted" : "-1.66",  "Weighted Average Shs Out" : "39232269.0",  "Weighted Average Shs Out (Dil)" : "38529000.0",  "Dividend per Share" : "0.0",  "Gross Margin" : "0.8044",  "EBITDA Margin" : "-0.033",  "EBIT Margin" : "-0.0791",  "Profit Margin" : "-0.124",  "Free Cash Flow margin" : "0.1002",  "EBITDA" : "-17146000.0",  "EBIT" : "-40574000.0",  "Consolidated Income" : "-63828000.0",  "Earnings Before Tax Margin" : "-0.1208",  "Net Profit Margin" : "-0.1244"}api端點的json示例如下: financialmodelingprep.com我的問題是,當我對此進行解碼時,我最終得到的是對象/字符串,而不是浮點數或整數。我試過了:r = requests.get(url, params)jd = json.loads(r.text)也:r = requests.get(url, params)jd - r.json()并且,還有使用 kwargs 的變體,例如 parse_float = float 或 parse_float=Decimal我的最終目標是使用浮點數、整數和日期將其轉換為格式。
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

我最終需要為我的 json 解碼器編寫一個自定義對象掛鉤。


我還決定添加一個camelizer來縮短鍵。


import requests

import re

import json

from datetime import datetime


quarterdateformat = '%Y-%m-%d'



def camelize(string):

    return "".join(string.split(" "))


def convert_types(d):

    for k, v in d.items():

        #print(k, type(v))

        new_v = v

        if type(v) is str:

            #match for float

            if re.match('[-+]?[0-9]*\.[0-9]+', v):  

                new_v = float(v)


            #match for date

            if re.match('([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))', v):  

                new_v = datetime.strptime(v, quarterdateformat).date()



        d[k] = new_v

    d = {camelize(k): v for k, v in d.items()}

    return d


url = "https://financialmodelingprep.com/api/v3/financials/income-statement/CRM,HUBS"

params = {'datatyupe' : 'json'}

r = requests.get(url, params)

jd= json.loads(r.text, object_hook=convert_types)

convert_types 是對象掛鉤函數,它使用正則表達式來查找浮點數和日期并轉換它們。Camelizer 用于在對象掛鉤的末尾將所有鍵轉換為 CamelCase。


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號