JSON.stringify可以输出格式化为double的整数吗? [英] Can JSON.stringify output a whole number formatted as a double?

查看:215
本文介绍了JSON.stringify可以输出格式化为double的整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在做的一个例子:

This is an example of what I'm doing:



var serialized = JSON.stringify({x: 1.0});

这就是我想要的结果:



{"x": 1.0}

但这是我得到的结果:



{"x": 1}

我尝试过使用 JSON.stringify的第二个参数



JSON.stringify({x: 1.0}, function (k, v) {
  if (Number.isInteger(v)) {
    return v.toFixed(1);
  }
  return v;
});

但这不能得到我想要的东西:

But that doesn't get me what I want either:



{"x": "1.0"}

查看 JSON.stringify 的JSON / stringifyrel =nofollow>文档,我没有看到一个明显的方法来实现我想做的事情。是否有一种解决方法或我缺少的东西?

Looking at the documentation for JSON.stringify, I don't see an obvious way to get this to do what I want. Is there a workaround or something I'm missing?

对于上下文,我正在获取序列化数据并将其传递给elasticsearch集群,我想要弹性搜索动态为 x 字段创建映射(在示例中)。但是,如果elasticsearch看到的第一个数字是 1 而不是 1.0 ,它将创建一个长映射而不是双映射和未来的双 x 值(例如 1.5 )会导致elasticsearch解析失败。

For context, I'm taking the serialized data and passing it to an elasticsearch cluster, and I want elasticsearch to dynamically create a mapping for the x field (in the example). However, if the first number that elasticsearch sees is 1 and not 1.0, it will create a long mapping instead of a double mapping, and future double x values (e.g. 1.5) would cause elasticsearch parsing to fail.

推荐答案

考虑使用JSON.stringify的替换器函数和String#replace并添加一个小数字来寻找要替换的整数。

Taking the idea of a using the replacer function of JSON.stringify and String#replace and a small addition to the number for finding the integer to replace.

它可能如下所示:

var s = JSON.stringify({ x: 1.0 }, function (k, v) {
        if (Number.isInteger(v)) {
            return v + 1e-10;
        }
        return v;
    }).replace(/\.0000000001/, '.0');

console.log(s);

这篇关于JSON.stringify可以输出格式化为double的整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆