NeatJSON
Pretty-print your JSON in Ruby, JS, or Lua with more power than JSON.stringify or JSON.pretty_generate
Install / Use
/learn @Phrogz/NeatJSONREADME
NeatJSON
Pretty-print your JSON in Ruby, JavaScript, Lua, or Python with more power than is provided by JSON.pretty_generate (Ruby), JSON.stringify (JS), or json.dumps (Python). For example, like Ruby's pp (pretty print), NeatJSON can keep objects on one line if they fit, but break them over multiple lines if needed.
Features:
- Online webpage for performing conversions and experimenting with options.
- Modifying graphical options on the webpage also gives you the JS code you would need to call to get the same results.
- Keep multiple values on one line, with variable wrap width.
- Format numeric values to specified decimal precision.
- Optionally force specific keys to use floating point representation instead of bare integers for whole number values (e.g.
42.0instead of42).
- Optionally force specific keys to use floating point representation instead of bare integers for whole number values (e.g.
- Sort object keys to be in alphabetical order.
- Arbitrary whitespace (or really, any string) for indentation.
- "Short" wrapping uses fewer lines, indentation based on values. (See last example below.)
- Indent final closing bracket/brace for each array/object.
- Adjust number of spaces inside array/object braces.
- Adjust number of spaces before/after commas and colons (both for single- vs. multi-line).
- Line up the values for an object across lines.
- [Lua only] Produce Lua table serialization.
Table of Contents
Installation
- Ruby:
gem install neatjson - JavaScript (web): Clone the GitHub repo and copy
javascript/neatjson.js - Node.js:
npm install neatjson - Python:
pip install neatjson
Usage
Ruby:
require 'neatjson'
json = JSON.neat_generate( value, options )
JavaScript (web):
<script type="text/javascript" src="neatjson.js"></script>
<script type="text/javascript">
var json = neatJSON( value, options );
</script>
Node.js:
const { neatJSON } = require('neatjson');
var json = neatJSON( value, options );
Lua:
local neatJSON = require'neatjson'
local json = neatJSON(value, options)
Python:
from neatjson import neat_json
json_str = neat_json(value, **options)
Examples
The following are all in Ruby, but similar options apply in JavaScript, Lua, and Python.
require 'neatjson'
o = { b:42.005, a:[42,17], longer:true, str:"yes\nplease" }
puts JSON.neat_generate(o)
#=> {"b":42.005,"a":[42,17],"longer":true,"str":"yes\nplease"}
puts JSON.neat_generate(o, sort:true)
#=> {"a":[42,17],"b":42.005,"longer":true,"str":"yes\nplease"}
puts JSON.neat_generate(o,sort:true,padding:1,after_comma:1)
#=> { "a":[ 42, 17 ], "b":42.005, "longer":true, "str":"yes\nplease" }
puts JSON.neat_generate(o, sort:true, wrap:40)
#=> {
#=> "a":[42,17],
#=> "b":42.005,
#=> "longer":true,
#=> "str":"yes\nplease"
#=> }
puts JSON.neat_generate(o, sort:true, wrap:40, decimals:2)
#=> {
#=> "a":[42,17],
#=> "b":42.01,
#=> "longer":true,
#=> "str":"yes\nplease"
#=> }
puts JSON.neat_generate(o, sort:->(k){ k.length }, wrap:40, aligned:true)
#=> {
#=> "a" :[42,17],
#=> "b" :42.005,
#=> "str" :"yes\nplease",
#=> "longer":true
#=> }
puts JSON.neat_generate(o, sort:true, wrap:40, aligned:true, around_colon:1)
#=> {
#=> "a" : [42,17],
#=> "b" : 42.005,
#=> "longer" : true,
#=> "str" : "yes\nplease"
#=> }
puts JSON.neat_generate(o, sort:true, wrap:40, aligned:true, around_colon:1, short:true)
#=> {"a" : [42,17],
#=> "b" : 42.005,
#=> "longer" : true,
#=> "str" : "yes\nplease"}
a = [1,2,[3,4,[5]]]
puts JSON.neat_generate(a)
#=> [1,2,[3,4,[5]]]
puts JSON.pretty_generate(a) # oof!
#=> [
#=> 1,
#=> 2,
#=> [
#=> 3,
#=> 4,
#=> [
#=> 5
#=> ]
#=> ]
#=> ]
puts JSON.neat_generate( a, wrap:true, short:true )
#=> [1,
#=> 2,
#=> [3,
#=> 4,
#=> [5]]]
data = ["foo","bar",{dogs:42,piggies:{color:'pink', tasty:true},
barn:{jimmy:[1,2,3,4,5],jammy:3.141592653,hot:"pajammy"},cats:7}]
opts = { short:true, wrap:60, decimals:3, sort:true, aligned:true,
padding:1, after_comma:1, around_colon_n:1 }
puts JSON.neat_generate( data, opts )
#=> [ "foo",
#=> "bar",
#=> { "barn" : { "hot" : "pajammy",
#=> "jammy" : 3.142,
#=> "jimmy" : [ 1, 2, 3, 4, 5 ] },
#=> "cats" : 7,
#=> "dogs" : 42,
#=> "piggies" : { "color":"pink", "tasty":true } } ]
Options
You may pass any of the following options to neat_generate (Ruby), neatJSON (JavaScript/Lua), or neat_json (Python).
Note: camelCase option names below use snake_case in Ruby and Python, with Python using keyword arguments instead of an options dict. For example:
// JavaScript
var json = neatJSON( myValue, { arrayPadding:1, afterComma:1, beforeColonN:2 } );
-- Lua
local json = neatJSON( myValue, { arrayPadding=1, afterComma=1, beforeColonN=2 } )
# Ruby
json = JSON.neat_generate my_value, array_padding:1, after_comma:1, before_colon_n:2
# Python
json_str = neat_json(my_value, array_padding=1, after_comma=1, before_colon_n=2, indent_last=True)
wrap— Maximum line width before wrapping. Usefalseto never wrap,trueto always wrap. default:80indent— Whitespace used to indent each level when wrapping. default:" "(two spaces)indentLast— Indent the closing bracket/brace for arrays and objects? default:falseshort— Put opening brackets on the same line as the first value, closing brackets on the same line as the last? default:false- This causes the
indentandindentLastoptions to be ignored, instead basing indentation on array and object padding.
- This causes the
sort— Sort objects' keys in alphabetical order (true), or supply a lambda for custom sorting. default:false- If you supply a lambda to the
sortoption, it will be passed three values: the (string) name of the key, the associated value, and the object being sorted, e.g.{ sort:->(key,value,hash){ Float(value) rescue Float::MAX } }
- If you supply a lambda to the
aligned— When wrapping objects, line up the colons (per object)? default:falsedecimals— Decimal precision for non-integer numbers; usefalseto keep values precise. default:falsetrimTrailingZeros— Remove extra zeros at the end of floats, e.g.1.2000becomes1.2. default:falseforceFloats— Force every integer value written to the file to be a float, e.g.12becomes12.0. default:falseforceFloatsIn— Specify an array of object key names under which all integer values are treated as floats. For example, serializing{a:[1, 2, {a:3, b:4}], c:{a:5, d:6}withforceFloatsIn:['a']would produce{"a":[1.0, 2.0, {"a":3.0, "b":4}], "c":{"a":5.0, "d":6}}.arrayPadding— Number of spaces to put inside brackets for arrays. default:0objectPadding— Number of spaces to put inside braces for objects. default:0padding— Shorthand to set botharrayPaddingandobjectPadding. default:0beforeComma— Number of spaces to put before commas (for both arrays and objects). default:0afterComma— Number of spaces to put after commas (for both arrays and objects). default:0aroundComma— Shorthand to set bothbeforeCommaandafterComma. default:0beforeColon1— Number of spaces before a colon when the object is on one line. default:0afterColon1— Number of spaces after a colon when the object is on one line. default:0beforeColonN— Number of spaces before a colon when the object is on multiple lines. default:0afterColonN— Number of spaces after a colon when the object is on multiple lines. default:0beforeColon— Shorthand to set bothbeforeColon1andbeforeColonN. default:0afterColon— Shorthand to set bothafterColon1andafterColonN. default:0aroundColon— Shorthand to set bothbeforeColonandafterColon. default:0lua— (Lua only) Output a Lua table literal instead of JSON? default:falseemptyTablesAreObjects— (Lua only) Should{}in Lua become a JSON object ({}) or JSON array ([])? default:false(array)
You may omit the 'value' and/or 'object' parameters in your sort lambda if desired. For example:
# Ruby sorting examples
obj = {e:3, a:2, c:3, b:2, d:1, f:3}
JSON.neat_generate obj, sort:true # sort by key name
#=> {"a":2,"b":2,"c":3,"d":1,"e":3,"f":3}
JSON.neat_generate obj, sort:->(k){ k } # sort by key name (long way)
#=> {"a":2,"b":2,"c":3,"d":1,"e":3,"f":3}
JSON.neat_generate obj, sort:->(k,v){ [-v,k] } # sort by descending value, then by ascending key
#=> {"c":3,"e":3,"f":3,"a":2,"b":2,"d":1}
JSON.neat_generate obj, sort:->(k,v,h){ h.values.count(v) } # sort by count of keys with same value
#=> {"d":1,"a":2,"b":2,"e":3,"c":3,"f":3}
// JavaScript sorting examples
var obj = {e:3, a:2, c:3, b:2, d:1, f:3};
neatJSON( obj, {sort:true} ); // sort by key name
// {"a":2,"b":2,"c":3,"d":1,"e":3,"f":3}
neatJSON( obj, { sort:function(k){ return k }} ); // sort by key name (long way)
// {"a":2,"b":2,"c":3,"d":1
