[英]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.