簡體   English   中英

如何擺脫因將科學記數法轉換為精確值而產生的 json 字符串中的引號

[英]How to get rid of quotes in a json string resulting from converting scientific notation to exact value

我有一個字典項列表,我將遍歷這些項以更新為字典。 該字典將轉換為 json 字符串,該字符串將插入到 SQL 數據庫中。 我的問題是字典項中的某些值可能非常小(或大),因此 Python 會自動將其放入科學記數法中。

例如,我有這本字典: {"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}} 我已經能夠使用我在下面創建的函數將科學記數法轉換為精確的值字符串。 但是現在我必須將它保留為字符串,因為一旦我在該字符串上使用float() ,它就會返回到科學記數法。 因此,當我使用json.dumps()將字典放入 json 字符串時,它會在這些字符串轉換的浮點值周圍創建不必要的引號: "{"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}" . 我如何擺脫這些報價?

def format_float(self, value):
    value_string = str(value)
    # Anything smaller than or equal to 1e-5 will get converted to scientific notation
    # If the value is in scientific notation
    if 1e-323 <= abs(value) <= 1e-5:
        # Split the string by the exponent sign
        split_value_string = value_string.split("e-")
        # Get the exponential
        exponential = int(split_value_string[1])
        # If there is a decimal, there could be digits after the decimal
        if "." in split_value_string[0]:
            precision = len(split_value_string[0].split(".")[1])
        else:
            precision = 0
        f = "%.*f" % (exponential + precision, value)
    elif value == float("inf") or value == float("-inf"):
        return value
    # Not in scientific notation
    else:
        if "." in value_string:
            precision = len(value_string.split(".")[1])
        else:
            precision = 0
        f = "%.*f" % (precision, value)
    # No decimal
    if "." not in f:
        f += ".0"

    p = f.partition(".")

    s = "".join((p[0], p[1], p[2][0], p[2][1:].rstrip("0")))  # Get rid of the excess 0s

    return s

float()不應該把任何東西都放在科學記數法中。 只是當python打印一個很長的float ,它以科學計數法打印。 嘗試使用json.dumps()同時將值保持為float ,它應該給你你想要的。

編輯:讓我改寫。 json.dumps()會給你有效的 json。 json 規范允許將浮點數作為科學記數法給出,因此它采用科學記數法這一事實應該不成問題。 也就是說,如果您加載已轉儲的內容,它將為您提供一個float ,您可以按預期進行數學運算。 例如: type(json.loads(json.dumps({'lol':1e-8}))['lol'])給我float

如果您真的需要讓 json 沒有科學記數法,例如,如果讀取 json 的東西不符合標准,那么您可以使用json.dumps()將其轉儲為字符串,然后使用re.sub()替換數字。

precision = 10
re.sub('\d+e-?\d+',lambda x: '%.*f'%(precision,float(x.group())),json.dumps({'lol':1e-8}))

給我

'{"lol": 0.0000000100}'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM