Last active
September 11, 2024 18:13
-
-
Save jvon1904/44f352f3809dfa83a56442a4083b54d8 to your computer and use it in GitHub Desktop.
Ruby, Pretty generate inline JSON
This file contains hidden or 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
| # 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