Skip to content

Instantly share code, notes, and snippets.

@jvon1904
Last active September 11, 2024 18:13
Show Gist options
  • Select an option

  • Save jvon1904/44f352f3809dfa83a56442a4083b54d8 to your computer and use it in GitHub Desktop.

Select an option

Save jvon1904/44f352f3809dfa83a56442a4083b54d8 to your computer and use it in GitHub Desktop.
Ruby, Pretty generate inline JSON
# Below is a way to add a JSON module method #pretty_inline to receive a Ruby Hash and generate pretty JSON.
# This is similar to #pretty_generate only instead of adding indentation and newlines, this
# will produce an inline String.
#
# Under the hood, the method uses the JSON#generate method which accepts a 2nd optional argument of options.
#
# :object_nl (object newline) - normally a newline character (\n) but in this case, just a space. This will be
# inside curly braces and after commas
#
# :array_nl (array newline) - normally a newline character (\n) but in this case, just a space as well. This will
# inside square brackets
#
# :indent - no indentation
#
# :space - add a space after colons (:)
#
# Example:
#
# ruby_hash = {a:1,b:2,c:{c1:1,c2:2,c3:3},d:[1,2,3,4,5]}
# => {:a=>1, :b=>2, :c=>{:c1=>1, :c2=>2, :c3=>3}, :d=>[1, 2, 3, 4, 5]}
#
# JSON.pretty_inline(ruby_hash)
# => "{ \"a\": 1, \"b\": 2, \"c\": { \"c1\": 1, \"c2\": 2, \"c3\": 3 }, \"d\": [ 1, 2, 3, 4, 5 ] }"
#
# puts _
# { "a": 1, "b": 2, "c": { "c1": 1, "c2": 2, "c3": 3 }, "d": [ 1, 2, 3, 4, 5 ] }
#
require 'json'
def JSON.pretty_inline(ruby)
generate(ruby, space: ' ', object_nl: ' ', array_nl: ' ')
end
# Or
#
# module JSON
# def self.pretty_inline(ruby)
# generate(ruby, space: ' ', object_nl: ' ', array_nl: ' ')
# end
# end
#
# Or
#
# module JSON
# class << self
# def pretty_inline(ruby)
# generate(ruby, space: ' ', object_nl: ' ', array_nl: ' ')
# end
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment