JSON Minify — Ruby source
Remove all whitespace from JSON for the most compact serialization. Validates as it minifies, runs entirely in your browser, with a shareable link to your exact input.
This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# json-minify — compact JSON to its smallest valid form. Ruby port (canonical
# TS: src/lib/json-minify.ts; Go twin: cli/json-minify). Mirrors the JS/PHP
# ports: parse, then re-emit compact via Ruby's bundled 'json' stdlib.
require 'json'
module JsonMinify
module_function
# Compact serialization of input, or nil for invalid JSON — same inputs ->
# same outputs as the TS / Go references. JSON.generate is compact by
# default and never escapes '/' or non-ASCII, matching Go json.Compact and
# JS JSON.stringify. allow_nan: false rejects the non-standard NaN /
# Infinity tokens that Go's grammar also rejects (the Python port's
# parse_constant analogue). Hash keeps insertion order, so key order holds.
def minify(input)
JSON.generate(JSON.parse(input, allow_nan: false))
rescue JSON::ParserError, JSON::NestingError
nil
end
end
if __FILE__ == $PROGRAM_NAME
puts JsonMinify.minify("{\n \"a\": 1,\n \"b\": [\n 1,\n 2\n ]\n}") # {"a":1,"b":[1,2]}
puts JsonMinify.minify('{invalid}').inspect # nil — invalid JSON
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 →