Created
April 4, 2014 19:09
-
-
Save timuruski/9981201 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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 | |
stack.push char | |
when RBRACE, RBRACKET | |
stack.pop | |
buffer << char | |
when COLON | |
buffer << ': ' | |
when COMMA | |
buffer << char | |
else | |
buffer << char | |
end | |
end | |
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