简体   繁体   English

如何摆脱因将科学记数法转换为精确值而产生的 json 字符串中的引号

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

I have a list of dictionary items that I will iterate through to update into a dictionary.我有一个字典项列表,我将遍历这些项以更新为字典。 That dictionary will be converted to a json string which will get inserted into an SQL database.该字典将转换为 json 字符串,该字符串将插入到 SQL 数据库中。 My problem is that some of those values in the dictionary items can be very small (or large), and thus Python automatically puts it in scientific notation.我的问题是字典项中的某些值可能非常小(或大),因此 Python 会自动将其放入科学记数法中。

For example, I have this dictionary: {"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}} .例如,我有这本字典: {"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}} I've been able to convert scientific notation to an exact value string using the function that I created below.我已经能够使用我在下面创建的函数将科学记数法转换为精确的值字符串。 But now I have to keep it as a string because as soon as I cast float() on that string, it goes back to scientific notation.但是现在我必须将它保留为字符串,因为一旦我在该字符串上使用float() ,它就会返回到科学记数法。 So then when I use json.dumps() to put the dictionary into a json string, it creates unnecessary quotes around those string-casted float values: "{"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}" .因此,当我使用json.dumps()将字典放入 json 字符串时,它会在这些字符串转换的浮点值周围创建不必要的引号: "{"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}" . How do I get rid of those quotes?我如何摆脱这些报价?

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() shouldn't be putting anything in scientific notation. float()不应该把任何东西都放在科学记数法中。 It's just that when python prints a float that's really long, it prints it in scientific notation.只是当python打印一个很长的float ,它以科学计数法打印。 try using json.dumps() while keeping the values as float , it should give you what you want.尝试使用json.dumps()同时将值保持为float ,它应该给你你想要的。

edit : let me rephrase.编辑:让我改写。 json.dumps() will give you valid json. json.dumps()会给你有效的 json。 the json specification allows for floats to be given as scientific notation, so the fact that it's in scientific notation shouldn't be a problem. json 规范允许将浮点数作为科学记数法给出,因此它采用科学记数法这一事实应该不成问题。 That is, if you load what has been dumped, it will give you a float , which you can do math on as you would expect.也就是说,如果您加载已转储的内容,它将为您提供一个float ,您可以按预期进行数学运算。 eg: type(json.loads(json.dumps({'lol':1e-8}))['lol']) gives me float例如: type(json.loads(json.dumps({'lol':1e-8}))['lol'])给我float

If you REALLY need to have the json not have scientific notation in it, for example if the thing that will read the json is not standards-compliant, then you can use json.dumps() to dump it as a string, then use re.sub() to replace the numbers.如果您真的需要让 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}))

gives me给我

'{"lol": 0.0000000100}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM