I want a JSON array to contain all integers between 0 and 1000, but I don’t want to declare each element of that very long array individually. Is there a more economical/elegant way to declare that array in a JSON file?
Can I declare an array of integers in JSON without listing each element explicitly?
63 Views Asked by Felipe Evaristo At
2
There are 2 best solutions below
0
On
No, you can't. However, JSON is just a convenient way to serialize and de-serialize data and has a mechanism to restore data, called reviver.
For the task you want, assuming you want the property numbers to be an array of 0 to 1000, I'd do this:
{
"foo": "bar",
"numbers": "0-1000"
}
And, when you parse it, you can use the reviver function:
const jsonString = `
{
"foo": "bar",
"numbers": "0-1000"
}
`;
const obj = JSON.parse(jsonString, (key, val) => {
if (key !== "numbers") return val;
const res = [];
const [ low, high ] = val.split("-");
for (let i = +low; i <= +high; i++) {
res.push(i);
}
return res;
});
console.log(obj);
No, all elements in JSON must be listed explicitly. Of course if you are producing this JSON document from some script/program there will surely be terser ways to generate it, but the resulting JSON will list all the elements without shortcuts.