GithubHelp home page GithubHelp logo

phrogz / neatjson Goto Github PK

View Code? Open in Web Editor NEW
108.0 108.0 20.0 213 KB

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

HTML 15.20% JavaScript 25.42% Ruby 28.93% Lua 30.45%
javascript json lua ruby

neatjson's People

Contributors

ebouchut avatar nomoon avatar phrogz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

neatjson's Issues

Circular references not detected/handled.

/home/ubuntu/workspace/jsbot/node_modules/neatjson.js:45
                        }else if (o instanceof Array){
                                    ^

RangeError: Maximum call stack size exceeded

with some huge objects:

and prettifier code:

Add comma-first formatting style.

In case people like the crazy.

var o =
    { a : "ape"
    , b : "bat"
    , c : "cat"
    , d : "dog"
    , e : "elf"
    , f : "fly"
    , g : "gnu"
    , h : "hat"
    , i : "ibu"
    }
  , a = 
    [ [ "ape", "bat" ]
    , [ "cat", "dog" ]
    , [ "elf", "fly" ]
    , [ "gnu", "hat" ]
    , [ "ibu" ]
    ];

More arguments for it here.

can't get the wrap option to work ?

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.

Hash plus short formatting plus wrapping values incorrect.

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"}

npm module

Very nice module, It would be nice if you publish the same on npm also.

Split options for comma spacing for arrays versus objects

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.

neat formatting seems to ignore hash levels deeper than 2

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": {}
}

Feature request

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.

Failed formatting for this JSON object

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. (?!)

Compact output (some values on one line)

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.

Print large arrays in a grid

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).

Bug: Strings containing # sign are escaped unecessarily

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.

Would like to have an explicit control over sorting the keys

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]]}``

  • the first array lists elements to be sorted at the beginning
  • the second array lilsts elements to be sorted to the ends
  • elements in none of the two lists are placed inbetween, either in input order or controlled by sort option.

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.

neatjson Ruby gem does not include JavaScript version

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.

Lua version has improper character escaping

~/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.

trimTrailingZeros breaks indentation

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.

Wrong output for short:true with specific array of hashes

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"}]}

Could we have more fine control over line breaks

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:

  • policies, keys, display start on a new line and are formatted as an indented block
  • content of keys; is never wrapped

Of course there is lots of possible desires:

  • consider object in content
  • inlineWrap which would add linebreak not on every element but only if the line is full

....

Multiline Lua output incorrectly quotes keys

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
--> }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.