Skip to content

JSON Formatter — Ruby source

Beautify, minify and validate JSON instantly. Paste, format, copy - all in your browser. Share a link to your exact input.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# frozen_string_literal: true

# json-formatter — parse, pretty-print (2-space indent), and minify.
#
# Language: Ruby (Ruby 3.2, bundled standard library: json)
# Source:   CosmoDev polyglot showcase port of the `json-formatter` tool,
#           ported from src/tools/JsonFormatter.tsx (the canonical
#           TypeScript island).
# License:  display source — part of CosmoDev's polyglot tool pages.
#
# Unlike the Rust/C/C++/Java ports (hand-written parsers), Ruby ships a JSON
# engine with the language, so — like the Python port — this file leans on
# it: JSON.parse builds Ruby objects (Hash preserves insertion order, same
# as a JavaScript engine), JSON.generate emits compact JSON with no
# whitespace, and JSON.pretty_generate emits the indented shape (": "
# after keys, "[]" / "{}" for empty containers, matching the island's
# JSON.stringify(parsed, null, 2)).
#
# Parity caveats versus the TypeScript port (same as Python's): Ruby
# preserves float notation ("1.0", "1e3") where JSON.stringify normalizes
# ("1", "1000"), and Ruby Integers are arbitrary-precision, so large
# integer literals round-trip unchanged rather than snapping to the nearest
# double. Non-ASCII characters stay unescaped (generate is not in
# script_safe mode). Parse errors raise JSON::ParserError, whose message
# carries the nature and position of the failure.

require 'json'

# Mirrors the TypeScript { output, error } shape; error == nil means
# success or empty input. (Data is Ruby 3.2's immutable value type; its
# members take no defaults, so error is passed explicitly at every site.)
FormatResult = Data.define(:output, :error)

def format_json(input, mode: :beautify, indent: 2)
  # - empty / whitespace-only input -> empty output, no error
  # - valid JSON + :minify   -> compact JSON (no whitespace)
  # - valid JSON + :beautify -> indent-space-indented JSON
  # - invalid JSON           -> empty output, error message
  raw = input.strip
  return FormatResult.new(output: '', error: nil) if raw.empty?

  parsed = JSON.parse(raw)
  output =
    if mode == :minify
      JSON.generate(parsed)
    else
      JSON.pretty_generate(parsed, indent: ' ' * indent)
    end
  FormatResult.new(output:, error: nil)
rescue JSON::ParserError => e
  FormatResult.new(output: '', error: e.message)
end

if $PROGRAM_NAME == __FILE__
  sample = '{"name":"CosmoDev","tools":["json","base64"],"free":true,"nested":{"ok":1}}'
  result = format_json(sample)
  puts result.error || result.output
end

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →