phrogz / neatjson Goto Github PK
View Code? Open in Web Editor NEWPretty-print your JSON in Ruby, JS, or Lua with more power than JSON.stringify or JSON.pretty_generate
Home Page: http://phrogz.net/JS/NeatJSON
License: MIT License
Pretty-print your JSON in Ruby, JS, or Lua with more power than JSON.stringify or JSON.pretty_generate
Home Page: http://phrogz.net/JS/NeatJSON
License: MIT License
Input:
["#{test}"]
Pry log of failure:
[1] pry(main)> require 'neatjson'
true
[2] pry(main)> test = JSON.parse(File.open('test.json').read)
[
[0] "\#{test}"
]
[3] pry(main)> puts test.to_json
["#{test}"]
nil
[4] pry(main)> puts JSON.neat_generate(test)
["\#{test}"]
nil
When outputting the test file with native to_json, the # isn't escaped. When outputting using neat_generate, it is.
The approach to determine the line breaks by wrapping works in many - but not in all cases.
Would it be possible to provide a list of keys and applicable policies, for example
{
"wrap" : 40,
"policies" : [
{
"keys" : ["policies", "keys", "display"],
"display" : "block"
},
{
"contentOf" : ["keys"],
"display" : "inline"
}
]
}
This specifies:
Of course there is lots of possible desires:
....
In the neatjson gem on rubygems.org, you mention that it includes the JavaScript version, but the JavaScript version is not in the gem:
.
├── lib
│ └── neatjson.rb
├── LICENSE.txt
├── neatjson.gemspec
├── README.md
├── test
│ ├── large.json
│ ├── test_neatjson.js
│ ├── test_neatjson.rb
│ ├── tests.js
│ └── tests.rb
└── .yardopts
It'd probably be appropriate to move the javascript/
directory to vendor/assets/javascripts/
and recursively include the vendor/
directory in your gemspec. Here's an example from highlight_js-rails4 if it helps.
The before_comma
, after_comma
, around_comma
options apply to both single-line arrays and objects.
before_comma
should become a shorthand for before_array_comma
and before_object_comma
.after_comma
should become a shorthand for after_array_comma
and after_object_comma
.We cannot have around_array_comma
or around_object_comma
because these would conflict and cause (even more) confusing inheritance. But that's OK; spacing around commas is not usually symmetric.
the command to generate the below output is JSON.neat_generate(env, after_colon: 1, padding: 1)
. env
contains the ruby hash object used to generate the output.
the output somehow has the _template
hash all in one line, which is not expected:
{
"name": "foo",
"description": "some environment",
"cookbook_versions": {
...snip...
"seven_zip": "= 2.0.2",
"windows": "= 1.39.1",
"zookeeper": "= 9.0.1"
},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {
"blah": {
"_template": { "elb_logs_index_template": { "settings": { "number_of_shards": 6 } } }
}
},
"override_attributes": {}
}
the expected output is:
{
"name": "foo",
"description": "some environment",
"cookbook_versions": {
...snip...
"seven_zip": "= 2.0.2",
"windows": "= 1.39.1",
"zookeeper": "= 9.0.1"
},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {
"blah": {
"_template": {
"elb_logs_index_template": {
"settings": {
"number_of_shards": 6
}
}
}
}
},
"override_attributes": {}
}
local n = require('neatjson')
t = {foo=1, bar=2}
print(n(t, {lua=true, wrap=false}))
--> {foo=1,bar=2}
print(n(t, {lua=true, wrap=true}))
--> {
--> "foo"=1,
--> "bar"=2
--> }
a = [1,2]
neatJSON(a,{ wrap:true, indent:"", decimals:3, trimTrailingZeros:true })
// [
// 1,
// 2
// ]
neatJSON(a,{ wrap:true, short:true, decimals:3, trimTrailingZeros:true });
// 1,
// 2]
Expected output:
[1,
2]
{
"a" : {
"b" : 1,
"c" : 2
},
"b" : {
"b" : 1,
"c" : 2
}
}
Would e easier to read if the closing angle bracket is adjusted to the content
{
"a" : {
"b" : 1,
"c" : 2
},
"b" : {
"b" : 1,
"c" : 2
}
}
Hi,
Thanks for great gem but I'm failing to get the wrap option working. For me it doesn't seem to do anything. Maybe i miss-understood what it does.
Lets say i have:
{
"header_timestamp" : "2015-05-14 11:05:23",
"user" : "Mr Who",
"work_notes" : "Some super super super super super super super super super super super super super super super super super super super super super line",
"changed" : "blah blah"
}
And i use the wrap:40
option, that it would output the formatting like below.. so on the 40th character it would wrap the long line. ( ideally on the word boundary and not chop a word in half :) )
"work_notes" : "Some super super super super super super super sup
er super super super super super super super super
super super super super super line",
Reading the options description, maximum line width before wrapping
, isn't this what it does ?
If not, can you explain what it does and maybe this would be a good feature to add please.
Thanks again.
~/code/NeatJSON/test$ lua test_neatjson.lua
neatJSON("foo\9bar")
EXPECTED
"foo\tbar"
ACTUAL
"foo\9bar"
neatJSON("foo\13bar")
EXPECTED
"foo\rbar"
ACTUAL
"foo\13bar"
neatJSON("foo\8bar")
EXPECTED
"foo\bbar"
ACTUAL
"foo\8bar"
neatJSON("foo\12bar")
EXPECTED
"foo\fbar"
ACTUAL
"foo\12bar"
This is valid Lua escaping, but not valid JSON escaping. At a minimum need to convert \9
to \u0009
to be valid JSON; would be preferable to use the nicer escapes for \n
\t
\r
\f
.
o = {hooo:42,whee:%w[yaaa oooo booy],zoop:"whoop"}
puts JSON.neat_generate(o,wrap:20,short:true)
Expected output:
{"hooo":42,
"whee":["yaaa",
"oooo",
"booy"],
"zoop":"whoop"}
Actual output:
{"hooo":42,
"whee":["yaaa",
"oooo",
"booy"],
"zoop":"whoop"}
o = { a:[ {x:"foo",y:"jim"}, {x:"bar",y:"jam"} ] }
puts JSON.neat_generate o, wrap:true, short:true
Expected output:
{"a":[{"x":"foo",
"y":"jim"},
{"x":"bar",
"y":"jam"}]}
Actual output:
{"a":[{"x":"foo",
[ "y":"jim"},
{"x":"bar",
"y":"jam"}]}
Let's make legal JSON values that help the user, instead of null
.
"NaN"
9e9999
-9e9999
var obj = '{ "abcdefghij":[{ "abcdefghijklmnop":{} }] }';
var json = neatJSON(obj, {wrap:1, short:true, aroundColonN:1} );
// TypeError: Cannot read property '0' of undefined
Removing characters from either property name fixes the problem, as does removing the aroundColonN
option. (?!)
// correct
neatJSON( {b:0,a:9,c:5}, {wrap:1, sort:true, short:true} );
// {"a":9,
// "b":0,
// "c":5}
// broken
neatJSON( {b:0,a:9,c:5}, {wrap:1, sort:true} );
// {
// "b":0,
// "a":9,
// "c":5
// }
EXPECTED:
// {
// "a":9,
// "b":0,
// "c":5
// }
{ "d": "10", "1":30 ,"a":10}
yields
{"1":30 ,"d":"10" ,"a":10}
It changes the sequence of the properties if the key is a string representing a number
Given an object like
{
:a => 1,
'b' => 2
}
Generating JSON with sort: true
fails with ArgumentError: comparison of Symbol with String failed
. This can be worked around by setting sort: ->(k) { k.to_s }
, but it seems like it should be handled by default.
For Ruby (or in general) it would be nice to be able to configure default options for neat_generate
. That is, options that are used of no options argument is provided to neat_generate
.
#22 solved the issue for sorting. But if opts.sort=function() ... it does not work, it always sorts alphabetically.
I will provide a test case
o = [1,2]
neatJSON(o,{ wrap:true, decimals:3 })
// [
// 1,
// 2
// ]
neatJSON(o,{ wrap:true, decimals:3, trimTrailingZeros:true });
// [
// 1,
// 2
// ]
Also affects short
formatting.
The sumary says it all.
I am looking for compact output but readable, here is my data:
[
{
"id": 1,
"product": "pumad",
"price": 48,
"color": "yellow",
"available": true,
"tags": [
"bravo"
],
"vendor": {
"name": "Lizzie Chapman",
"address": {
"city": "Mumbai"
}
}
},
{
"id": 2,
"product": "rupasge",
"price": 35,
"color": "red",
"available": true,
"tags": [
"delta"
],
"vendor": {
"name": "Ellen Harrison",
"address": {
"city": "New York"
}
}
}
]
with following command:
var json = neatJSON(obj,{ short:true, afterComma:1, afterColon1:1, afterColonN:1 });
output is:
[{"id": 1,
"product": "pumad",
"price": 48,
"color": "yellow",
"available": true,
"tags": ["bravo"],
"vendor": {"name": "Lizzie Chapman", "address": {"city": "Mumbai"}}},
{"id": 2,
"product": "rupasge",
"price": 35,
"color": "red",
"available": true,
"tags": ["delta"],
"vendor": {"name": "Ellen Harrison", "address": {"city": "New York"}}}]
My requirement is to get output wrapped at 80 col:
[{"id": 1, "product": "pumad", "price": 48, "color": "yellow",
"available": true, "tags": ["bravo"],
"vendor": {"name": "Lizzie Chapman", "address": {"city": "Mumbai"}}},
{"id": 2, "product": "rupasge", "price": 35, "color": "red",
"available": true, "tags": ["delta"],
"vendor": {"name": "Ellen Harrison", "address": {"city": "New York"}}}]
Would it be possible to get such output.
I am looking for this option to show the json data on stackoverflow or github issues or README file.
Very nice module, It would be nice if you publish the same on npm also.
I would like to have explicit control about the order of the keys. I have implemented in https://github.com/bwl21/NeatJSON/tree/feature/explicit_sort.
It is controlled by options:
`explicit_sort: [[:e, :d,],[:b, :a]]}``
This is the testcase
{value:{a:1, b:2, c:{a:1, b:2}, d: 3, e:4}, tests:[
{ json:%Q{{"e":4,"d":3,"c":{"b":2,"a":1},"b":2,"a":1}},
opts:{wrap:false, explicit_sort: [[:e, :d,],[:b, :a]]} },
{ json:%Q{{"e":4,"d":3,"b":2,"a":1,"c":{"b":2,"a":1}}},
opts:{wrap:false, explicit_sort: [[:e, :d,],[:b, :a, :c]]} },
{ json:%Q{{
"e":4,
"d":3,
"c":{
"b":2,
"a":1
},
"b":2,
"a":1
}},
opts:{wrap:1, explicit_sort: [[:e, :d,],[:b, :a]]} },
{ json:%Q{{"e":4,
"d":3,
"c":{"b":2,
"a":1},
"b":2,
"a":1}},
opts:{short:true, wrap:1, explicit_sort: [[:e, :d,],[:b, :a]]} }
]}
I can prepare a pull request if you would be willing to integrate that. It depends/conflicts with pr #15. So we should decide #15 one first.
neat_generate() fails on a deeply nested JSON doc that pretty_generate() handles correctly. It gets stuck and never returns. See example script here:
neatjson_fails.rb.txt
I like NeatJSON - great package!
I encountered a need to display JSON objects containing an array with 1000 to 2000 numbers. I was able to make NeatJSON to print it in one line or one column only, nothing else.
It would be extremely useful to have it print arrays in lines with as many numbers as fit across the given width, and end up with a more compact display. 1000 numbers can be 25 numbers by 40 lines - much better than 1000 lines vertically or 8000 chars horizontally with extremely long scrollbar.
A separate setting of how many elements to print across can be useful (e.g. when the data has certain repetition, and width limit is chosen for other reasons) .
A separate setting to pad all Array elements to the same width can be useful (so they show up aligned in columns).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.