Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

javascript - Can JSON.stringify output a whole number formatted as a double?

This is an example of what I'm doing:


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

And this is the result I want:


{"x": 1.0}

But this is the result I'm getting:


{"x": 1}

I've tried using the second argument to 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"}

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

It could look like this:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...