awesome-print / awesome_print

Pretty print your Ruby objects with style -- in full color and with proper indentation
http://github.com/michaeldv/awesome_print
MIT License
4.07k stars 454 forks source link

[feature] Support for json string's awesome print. #307

Open zfjoy520 opened 7 years ago

zfjoy520 commented 7 years ago

If I get a hash, string, CGI escaped string, query string, CGI escaped query string like follows:

require 'json'
require 'cgi'
require 'awesome_print'
require 'rack/utils'

h = {a: 1, b: 2, c: 'ooxx'}
# => {:a=>1, :b=>2, :c=>"ooxx"}

s = h.to_json
# => "{\"a\":1,\"b\":2,\"c\":\"ooxx\"}"

escaped_s = CGI.escape(s)
# => "%7B%22a%22%3A1%2C%22b%22%3A2%2C%22c%22%3A%22ooxx%22%7D"

q = h.to_query
# => "a=1&b=2&c=ooxx"

escaped_q = CGI.escape(q)
# => "a%3D1%26b%3D2%26c%3Dooxx"

A feature to awesome_print a json string or escaped json string, query string or CGI escaped query string like this:

>> ap h
{
    :a => 1,
    :b => 2,
    :c => "ooxx"
}
=> nil

>> ap s
{
  "a": 1,
  "b": 2,
  "c": "ooxx"
}
=> nil

>> ap escaped_s
{
  "a": 1,
  "b": 2,
  "c": "ooxx"
}
=> nil

>> ap q
{
  "a": "1",
  "b": "2",
  "c": "ooxx"
}
=> nil

>> ap escaped_q
{
  "a": "1",
  "b": "2",
  "c": "ooxx"
}
=> nil

I add a monkey patch like follows:

require 'json'
require 'cgi'
require 'rack/utils'
require 'awesome_print'

Kernel.module_exec do
  def ap(obj, options = {})
    if json_string?(obj)
      ap_json_string(obj, options)
    elsif query_string?(obj)
      ap_json_string(Rack::Utils.parse_nested_query(CGI.unescape(obj)).to_json, options)
    else
      awesome_print(obj, options)
    end
  end

  private

  def json_string?(obj)
    obj.is_a?(String) && CGI.unescape(obj) =~ /\A\s?{".+?}\Z/
  end

  def query_string?(obj)
    obj.is_a?(String) && CGI.unescape(obj) =~ /([^&]*=[^&]*)&?/
  end

  def ap_json_string(obj, options)
    puts JSON.pretty_generate(JSON.parse(CGI.unescape(obj))).red
  rescue
    awesome_print(obj, options)
  end
end
zfjoy520 commented 7 years ago

It's very useful for awesome_print http post body json string in verbose model for check.

imajes commented 7 years ago

that'd be a great PR!