Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created April 4, 2014 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuruski/9981201 to your computer and use it in GitHub Desktop.
Save timuruski/9981201 to your computer and use it in GitHub Desktop.
#! /usr/bin/ruby
LBRACE = '{'
RBRACE = '}'
LBRACKET = '['
RBRACKET = ']'
COMMA = ','
COLON = ':'
WHITESPACE = /\s/
# Very naively prints formatted JSON from a stream.
# This doesn't handle Strings or escapes or any other stuff like that.
#
# Usage:
# ruby pjson.rb minified.json
# curl http://example.com/index.json | ruby pjson.rb
class PJson
def initialize(input = ARGF, output = $stdout)
@input = input
@output = output
@stack = []
@buffer = ''
end
attr_reader :buffer, :stack
def format!
ARGF.each_char do |char|
case char
when WHITESPACE
# ignore
when LBRACE, LBRACKET
buffer << char
print
stack.push char
when RBRACE, RBRACKET
print
stack.pop
buffer << char
when COLON
buffer << ': '
when COMMA
buffer << char
print
else
buffer << char
end
end
print
end
def print
return if buffer.empty?
padding = (' ' * stack.length)
$stdout.puts (padding << buffer)
buffer.clear
end
end
PJson.new.format! if $0 == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment