module Common
  require 'json'
  $tabstops=ENV['JSON_INDENT'].to_i || 0;

  def stdin()
    return STDIN.read;
  end

  def parse()
    return convert(stdin());
  end

  def convert(data)
    parser = JSON::Ext::Parser.new(data,{:quirks_mode => true})
    return parser.parse();
  end

  def stringify(document,indent=-1)
    stops=$tabstops;
    if indent > -1
      stops=indent;
    end
    indentation=" " * stops;
    if stops > 0
      return JSON.pretty_generate(
        document,{:indent => indentation, :quirks_mode => true});
    else
      return JSON.generate(
        document,{:quirks_mode => true});
    end
  end

  def compact(document)
    return stringify(document,0);
  end
end
