JSON Pretty Generate

Small utility method for pretty generating JSON

Installation

Add this line to your application's Gemfile:

gem 'json_pretty_generate'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install json_pretty_generate

Usage

There is a single ::call method.

Argument is a Hash

When the argument is a Hash JSON will be returned with line breaks

obj = { a: 1 }
JSONPrettyGenerate.(obj)
# => "{\n  \"a\": 1\n}"

Argument is a String

When the argument is JSON it returns JSON with line breaks

obj = "{\"a\":1}"
JSONPrettyGenerate.(obj)
# => "{\n  \"a\": 1\n}"

When the argument is a string that is not JSON it returns the argument

obj = "a=1"
JSONPrettyGenerate.(obj)
# => "a=1"

Argument is not a String or a Hash

When the argument type is not a String or Hash it will return nil

obj = 1
JSONPrettyGenerate.(obj)
# => nil

Filtering with a block

You can use a block to filter the obj to a subset of the data. Strings or symbols can be passed to the block argument.

obj = { data: { body: { a: 1 } } }
JSONPrettyGenerate.(obj) { |o| o[:data][:body] }
# => "{\n  \"a\": 1\n}"

Development

To run the specs

  $  bundle exec rake

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nikkypx/json_pretty_generate.

License

The gem is available as open source under the terms of the MIT License.