3

I'm using Crystal's JSON module to update package.json files and all the output is on one line. Is it possible to control the output of :to_json?

require "JSON"
data = File.read("package.json")
data.as_h["version"] = "X.X.X"
puts data.to_json
dgo.a
  • 2,634
  • 23
  • 35

2 Answers2

6

Try using the .to_pretty_json() method. You can pass it an optional indent string: .to_pretty_json(" ")

It doesn't seem to be well-documented. But, here's the source: https://github.com/crystal-lang/crystal/blob/master/src/json/to_json.cr

dgo.a
  • 2,634
  • 23
  • 35
2

Object#to_pretty_json should get you far enough. If you need more customization, you could also call to_json(json : JSON::Builder) and implement a custom JSON::Builder.

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25