arraysjsonvariable-declaration

Can I declare an array of integers in JSON without listing each element explicitly?


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?


Solution

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