iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👌

Implementing a slightly more compact JSON.stringify

に公開

When you want to save JSON to a file, using JSON.stringify is common.

const obj = {a:{b:{c:{e:{f:["g",{h:["i"]}]}}}}, b:{c:"r"}}
JSON.stringify(obj)
// "{"a":{"b":{"c":{"e":{"f":["g",{"h":["i"]}]}}}},"b":{"c":"r"}}"

JSON.stringify allows you to insert spaces by providing a number as the third argument, such as JSON.stringify(obj, null, 2).

However, this causes everything to be nested.

{
  "a": {
    "b": {
      "c": {
        "e": {
          "f": [
            "g",
            {
              "h": [
                "i"
              ]
            }
          ]
        }
      }
    }
  },
  "b": {
    "c": "r"
  }
}

When saving a large JSON to a file, having no spacer makes it difficult to use when opening it in an editor, while setting spacer=2 makes the nesting too deep and hard to handle, as shown above.

Making a custom solution as a last resort

In my case, since one level of nesting was sufficient, something like the following seemed to be enough.

const jsonCompactStringify = (obj) => {
  const [s,e] = Array.isArray(obj) ? [`[`, `]`] : [`{`,`}`]
  return [s,
    Object.entries(obj)
      .map(([k, v]) => `  "${k}" : ${JSON.stringify(v)}`)
      .join(",\n")
  , e].join("\n")
}
jsonCompactStringify(obj)
// {
//   "a" : {"b":{"c":{"e":{"f":["g",{"h":["i"]}]}}}},
//   "b" : {"c":"r"}
// }

Objects and arrays only. If you want deeper nesting, you would likely need to run the above recursively.


By the way, Node.js's util.inspect has options like compact, but since this is intended for JavaScript-style representation, converting it to JSON seemed a bit difficult when considering things like escaping.

Discussion