2

Most JSON parsers have the option to generate a JSON-structured string as either "normal" (no extra whitespace) or "pretty" (whitespace added for easier human-readability).

The "pretty" version expands out objects and arrays into each property having its own line. But when an object is composed of a few short properties and values, it can be even more legible for humans to have it all on one line rather than a very tall and skinny visual.

Basically, I'm looking for a formatter that has further options for formatting JSON, like a "half-collapsed" formatting; where if the JSON object to be formatted fits well on one line, it doesn't get expanded out.

For example, given a JSON structure that if it were printed "pretty" it would be:

[
  {
    "type": "circle",
    "position": {
      "x": 100,
      "y": 100
    },
    "color": "red",
    "label": "Big Red",
    "radius": 50
  },
  {
    "type": "point",
    "position": {
      "x": 100,
      "y": 100
    }
  }
]

instead what I think is easier to read while also not needing as much scrolling is:

[
  {
    "type": "circle",
    "position": { "x": 100, "y": 100 },
    "color": "red",
    "label": "Big Red",
    "radius": 50
  },
  { "type": "point", "position": { "x": 100, "y": 100 }}
]

The "point" object is short enough that it can fit comfortably on one line, so it is presented that way. The "circle" object would be too long to fit on one line, but the sub-object of its "position" can be.

Is there a term for this "half-collapsed", "human-friendly, focused on paragrph-style line lengths" formatting? Any formatter or code-linting tool provide this sort of output?

1 Answer 1

2

You can do this with Underscore-CLI. Its pretty command outputs this kind of format by default, but you can also control the max width with --wrapwidth option.

E.g. with your data underscore pretty --in test.json --wrapwidth 100 outputs:

[
  {
    type: "circle",
    position: { x: 100, y: 100 },
    color: "red",
    label: "Big Red",
    radius: 50
  },
  { type: "point", position: { x: 100, y: 100 } }
]
2
  • The "pretty" format for that library appears to not actually be JSON. It outputs a Javascript-compatible output, but not strictly JSON, so couldn't be used to format an object to output as a *.json file. Mar 3, 2023 at 1:15
  • However, the "json" format (github.com/ddopson/underscore-cli#json; its default output) uses "smart whitespace", which is actually what I'm looking for! Mar 3, 2023 at 1:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.