I am writing an API in node.js that pulls data from a db, manipulates it, and sends it off to be consumed.
I have an object that looks like this:
{
2734899508: "Chicken",
2843594878: "Fish"
}
When I call JSON.stringify and pass the aforementioned object, I get this:
{
"2734899508": "Chicken",
"2843594878": "Fish"
}
I would like a string where the numeric keys are not turned into strings. How do I do this?
You could test whether each key/value is a stringified integer thus:
Note: using
==here intentionally rather than===because we want to coerce both to string.If, however, you know which keys/values are stringified ints, then you can just do the middle line to fix them.
I would point out that if you’re sending this json to a browser or other javascript client, it won’t really make a difference whether you have an int or a string, unless you always use
===.