skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search