Code Monkey home page Code Monkey logo

prettyjson's Introduction

prettyjson Build Status NPM version Coverage Status

Package for formatting JSON data in a coloured YAML-style, perfect for CLI output.

How to install

Just install it via NPM:

$ npm install -g prettyjson

This will install prettyjson globally, so it will be added automatically to your PATH.

Using it (from the CLI)

This package installs a command line interface to render JSON data in a more convenient way. You can use the CLI in three different ways:

Decode a JSON file: If you want to see the contents of a JSON file, just pass it as the first argument to the CLI:

$ prettyjson package.json

Example 1

Decode the stdin: You can also pipe the result of a command (for example an HTTP request) to the CLI to see the JSON result in a clearer way:

$ curl https://api.github.com/users/rafeca | prettyjson

Example 2

Decode random strings: if you call the CLI with no arguments, you'll get a prompt where you can past JSON strings and they'll be automatically displayed in a clearer way:

Example 3

Command line options

It's possible to customize the output through some command line options:

# Change colors
$ prettyjson --string=red --multiline_string=cyan --keys=blue --dash=yellow --number=green package.json

# Do not use colors
$ prettyjson --nocolor=1 package.json

# Change indentation
$ prettyjson --indent=4 package.json

# Render arrays elements in a single line
$ prettyjson --inline-arrays=1 package.json

# Escape conflictive strings
$ prettyjson --escape=1 package.json

Deprecation Notice: The old configuration through environment variables is deprecated and it will be removed in the next major version (1.0.0).

Using it (from Node.js)

It's pretty easy to use it. You just have to include it in your script and call the render() method:

var prettyjson = require('prettyjson');

var data = {
  username: 'rafeca',
  url: 'https://github.com/rafeca',
  twitter_account: 'https://twitter.com/rafeca',
  projects: ['prettyprint', 'connfu']
};

var options = {
  noColor: true
};

console.log(prettyjson.render(data, options));

And will output:

Example 4

You can also configure the colors of the hash keys and array dashes (using colors.js colors syntax):

var prettyjson = require('prettyjson');

var data = {
  username: 'rafeca',
  url: 'https://github.com/rafeca',
  twitter_account: 'https://twitter.com/rafeca',
  projects: ['prettyprint', 'connfu']
};

console.log(prettyjson.render(data, {
  keysColor: 'rainbow',
  dashColor: 'magenta',
  stringColor: 'white',
  multilineStringColor: 'cyan'
}));

Will output something like:

Example 5

Running Tests

To run the test suite first invoke the following command within the repo, installing the development dependencies:

$ npm install

then run the tests:

$ npm test

On windows, you can run the tests with:

C:\git\prettyjson> npm run-script testwin

prettyjson's People

Contributors

alexey-detr avatar bahamas10 avatar dabh avatar dgoguerra avatar dlight avatar endangeredmassa avatar exos avatar fengzilong avatar gotterdemarung avatar mercan01 avatar michaeldeboey avatar mmalecki avatar nem035 avatar pdehaan avatar rafeca avatar shaunmccarthy avatar sonicdoe avatar superpaintman avatar tiye avatar xhmikosr 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  avatar  avatar  avatar  avatar

prettyjson's Issues

possible unexpected coloring to the shell

649438969

Somewhat the shell was colored. everything after was green. But by re-running the very same node program(with prettyjson output, which should change text color repeatly), it was restored to normal.
My setup for prettyjson

var prettyjson = require('prettyjson')
var log = (obj) => console.log(prettyjson.render(obj, { }))
log(some_object)

Environment : Running directly in bash, color setting as

tput colors
> 8

Version of prettyjson

{ prettyjson: '1.1.3',
...

I couldn't repeat the bug, strangely. I suppose my node app was killed unexpectly.

maybe we can do some fix by listening process onexit?

Shouldn't it be installed globally?

Just found the project love the idea, I'm about to install it and I see npm install prettyjson in the docs is missing the global flag -g.

Option to limit depth/recursion?

For certain large objects, such as a Superagent response, prettyjson produces the following error message: "RangeError: Maximum call stack size exceeded".

I tried looking through the available options, but I didn't see anything immediately jumping out at me that would allow me to limit the depth or level of recursion that's happening within prettyjson. If the option isn't available, then perhaps this is a feature request.

Enumerable property flag is not respected

The 'enumerable' flag, which is specifically designed to squelch serialization of internal properties, is not respected in object output.

const prettyjson = require('prettyjson')

let data = {
  foo: 1,
  bar: 2
}

Object.defineProperty( data, 'bar', { enumerable: false } )

console.log( JSON.stringify( data, null, 2 ) )
/* Output: 
{
  "foo": 1
}
*/

console.log( prettyjson.render( data ) )
/* Output: 
foo: 1
bar: 2
*/

Inline (don't wrap) array of short values

Hi, thanks for the hard work on this awesome utility module.

To take advantage of horizontal instead of vertical screen space, can we have an option to change this:

installs:
  - 287
  - 239
  - 220
  - 186
  - 170
  - 247
  - 242
  - 280
  - 242
  - 275
  - 163
  - 183
  - 280
  - 335

To this:

installs: 287, 239, 220, 186, 170, 247, 242, 280, 242, 275, 163, 183, 280, 335

Breaking Change 1.2.0

The latest release (1.2.0) breaks existing functionality. Previously (1.1.3) the render method handled functions gracefully. When a function is encountered in the latest release, it recursively iterates through properties, of which are length,name,prototype,constructor, and appears to infinitely recurse on the constructor property (which makes sense if it is indeed a function).

Example object to render:

{
    key: "value",
    someAction: function(param) { return "obj." + param + ".value";}
}

Cli works, node version gives error

I try to print out large responses from an API pretty to the console. When using console.log(prettyjson.render(body)) I will get the normal output. When I save the response to a file and invoke the CLI version onto it, it works very fine (great job, still big thanks to you!).

I have decided to only save a smaller part of it and try it out, just to make sure it is not because of the size of the string. I have also linted it, but the JSON is valid. The excerpt is

{"sync_token":"CmkX2VYduo943FnaTQiSIah7TIcYViURLz-JtotQTX5l48Q4K_N65dcsj2XLkoZkUoBgTYT3pWH9cgdtGTo3iLDf4aVRIIclBCUaMuYVBqjK4KQ","temp_id_mapping":{},"labels":[{"item_order":8,"is_deleted":0,"name":"Bassam-Coles","color":6,"id":180356},{"item_order":6,"is_deleted":0,"name":"Computer_Science","color":7,"id":179952},{"item_order":1,"is_deleted":0,"name":"English","color":7,"id":179946},{"item_order":2,"is_deleted":0,"name":"German","color":7,"id":179947},{"item_order":12,"is_deleted":0,"name":"Hassan","color":6,"id":180363},{"item_order":4,"is_deleted":0,"name":"History","color":7,"id":179950},{"item_order":10,"is_deleted":0,"name":"Hoffmann","color":6,"id":180357},{"item_order":13,"is_deleted":0,"name":"Kr\u00fcger","color":6,"id":180364},{"item_order":16,"is_deleted":0,"name":"Mama","color":7,"id":703291},{"item_order":3,"is_deleted":0,"name":"Math","color":7,"id":179948},{"item_order":5,"is_deleted":0,"name":"Physics","color":7,"id":179951},{"item_order":11,"is_deleted":0,"name":"Scheibner","color":6,"id":180359},{"item_order":9,"is_deleted":0,"name":"Scott","color":6,"id":664961},{"item_order":15,"is_deleted":0,"name":"Tao","color":7,"id":198571},{"item_order":7,"is_deleted":0,"name":"Tok","color":7,"id":664960},{"item_order":14,"is_deleted":0,"name":"waiting","color":0,"id":188154}],"full_sync":true}

When using the following code, I get the error message displayed underneath

var prettyjson = require('prettyjson'),
    fs = require('fs');

var data = fs.readFile('todoistResponse');

var options = {
    noColors: true,
};

console.log(prettyjson.render(data, options));
Nicks-Air:node-todoist-api nicklehmann$ node pretty.js
/Users/nicklehmann/Desktop/node-todoist-api/node_modules/prettyjson/lib/utils.js:16
  Object.getOwnPropertyNames(input).forEach(function(key) {
         ^

TypeError: Cannot convert undefined or null to object
    at Function.getOwnPropertyNames (native)
    at Object.exports.getMaxIndexLength (/Users/nicklehmann/Desktop/node-todoist-api/node_modules/prettyjson/lib/utils.js:16:10)
    at renderToArray (/Users/nicklehmann/Desktop/node-todoist-api/node_modules/prettyjson/lib/prettyjson.js:141:52)
    at Object.render (/Users/nicklehmann/Desktop/node-todoist-api/node_modules/prettyjson/lib/prettyjson.js:210:10)
    at Object.<anonymous> (/Users/nicklehmann/Desktop/node-todoist-api/pretty.js:16:24)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)

I would be delighted to hear any advise!

New API to allow setting custom value display

Hello, thank you so much for this awesome library!

It would be helpful to allow passing a function like:

valueFormatter: (value) => {
  if (typeof value === 'string') {
    if (value.length === 0) return ['yellow', '(empty string)']
  }
  if (typeof value === 'undefined') {
    return ['yellow', '(undefined)']
  }
  if (typeof value === 'number') {
    return ['white', value]
  }
  return ['green', value]
}

Breaks when using with LESS

When I pipe the output of a long JSON file to LESS the colors go away.

prettyjson foo.json # works
prettyjson foo.json | less # no colors :cry: 

Discard non-json contents in curl requests

When using curl with -i or -v flags, it returns headers or debugging information of the request, that prettyjson is not parsing:

curl -i -X GET -H "Accept: application/json" "a_cool_json_resource" | prettyjson
...
Error: Not valid JSON!

Would be great if prettyjson just discards the non-json responses and write them like they are:

curl -i -X GET -H "Accept: application/json" "a_cool_json_resource" | prettyjson

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 20 Oct 2012 12:00:00 GMT

name: bla
age: ble
friends:
  -
    name: ...

Customizible boolean colors

Hi,
I need to customize boolean colors, true and false independently
Because red color is important for my log, and false uses that color. That's why I need this feature if possible.

By the way love the tool, thanks.

Security: Migrate from colors.js to some other library, fork, or a vendor-ed alternative

A short-term fix to lock prettyjson to a non-corrupt version of colors.js was shipped in #54 ๐ŸŽ‰ Great work!

Open Question: What's the longterm plan?

I use prettyjson/colors only as transitive dependencies, but I'm happy to contribute to make a long-term fix to prettyjson if you can explain which approach you prefer.

Options

A. keep colors.js pinned at 1.4.0 forever (end-users may have dependabot constantly trying to upgrade the lib)
B. drop colors (but the colors are pretty!)
C. replace colors.js with a vendored/in-house implementation -- My casual look at prettyjson's source is that we just need compatible implementations of colors/safe::(green|red|grey). I'm not sure of the licensing compatibilities, but it feels like this shouldn't be a very complicated API surface area to replace.
D. replace colors.js with a non-vulnerable fork. What fork should we pick?
E. replace colors.js with some other library. What library? -- chalk was suggested in #29
F. Do something else?

Dependencie on colors package breaks code.

Hi, please check Marak/colors.js#289 for all details.

Looks like the color package is deliberately broken so all dependencies break on update.

Would it be possible for now to update the package.json file to lock the colors package to the last stable version: 1.4.0

Kind regards

How about an options on stringColor?

The default terminal color is white and it looks not that pretty on my Archlinux.
According to your picture, the defualt color is more likely to be grey or some color like that.
Last night I wanted generate outputs similar to httpie, so I tried to folk it to add the feature.
Here's the code: https://github.com/jiyinyiyong/prettyjson/commits/master

The problem is, my code failed the tests.. I thinks it's still hard for me to finish it.
I mainly concern about that if there's technical barriers to add color for all strings?

Add option to disable sort

May you add a option to disable the sorting of the numeric object keys?

Example:

{
    "4": 6,
    "B": 1,
    "F": 9,
    "8": 4,
    "I": 3,
    "2": 13,
    "3": 7,
    "9": 13,
    "6": 19,
    "D": 6,
    "7": 2,
    "A": 1,
    "G": 3,
    "5": 4,
    "E": 3
}

results in

2: 13
3: 7
4: 6
5: 4
6: 19
7: 2
8: 4
9: 13
B: 1
F: 9
I: 3
D: 6
A: 1
G: 3
E: 3

Error parcing large file with only one row(40Mb json file)

When I try to do it from cli
Error: File 'messages.json' does not exist
When I try to do it from node

directory/node_modules/prettyjson/lib/prettyjson.js:167
      output.push.apply(
                  ^

RangeError: Maximum call stack size exceeded
    at directory/prettyjson/lib/prettyjson.js:167:19
    at Array.forEach (<anonymous>)
    at renderToArray (directory/node_modules/prettyjson/lib/prettyjson.js:145:36)
    at Object.render (directory/node_modules/prettyjson/lib/prettyjson.js:210:10)
    at Object.<anonymous> (directory/test.js:14:24)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)

Not skipping undefined attributes

Hey,

I know that undefined attributes are not valid JSON, so they are removed by JSON.parse. It would be helpful though to see these attributes for debugging purposes. Would you be open for a PR to change that behavior when using a specific option like showUndefined?

io.js compatibility

You have an engines field that doesn't really let io.js in. Is that something that could be addressed? Something tells me this module is perfectly capable of being used in io.js...

Log:

npm WARN engine [email protected]: wanted: {"node":">= 0.10.0 < 0.13.0"} (current: {"node":"3.0.0","npm":"2.13.3"})

Printing a regex

This is a really nice plugin. I was having some difficulty with regex expressions.
I have a regular expression in my JSON output. The plugin seems to be breaking out the regex into its characteristics.
For a regex

/\.js$|\.json$/

The plugin outputs

    source:     \.js$|\.json$
    global:     false
    ignoreCase: false
    multiline:  false
    lastIndex:  0

Is there a way for me to turn off this behavior?
Thanks!

"Keys" and "Values" are not aligned for longer "Values"

Issue - "Keys" and "Values" are not aligned for longer "Values"

Example - "description" section below. The indentation of value is not correct as in below response-
Pretty_Json_Key_Value_Alignment_Issue.txt

"notices": [
{
"title": "Terms of Use",
"description": [
"Access to Public Interest Registry RDAP information is provided to assist persons in determining the contents of a domain name registration record in the Public Interest registry database. The data in this record is provided by Public Interest Registry for informational purposes only, and Public Interest Registry does not guarantee its accuracy. This service is intended only for query-based access. You agree that you will use this data only for lawful purposes and that, under no circumstances will you use this data to(a) allow, enable, or otherwise support the transmission by e-mail, telephone, or facsimile of mass unsolicited, commercial advertising or solicitations to entities other than the data recipient's own existing customers; or (b) enable high volume, automated, electronic processes that send queries or data to the systems of Registry Operator, a Registrar, or Afilias except as reasonably necessary to register domain names or modify existing registrations. All rights reserved. Public Interest Registry reserves the right to modify these terms at any time. By submitting this query, you agree to abide by this policy."
],
"links": [
{
"rel": "alternate",
"href": "https://rdap.publicinterestregistry.net/rdap/org/terms_of_use",
"type": "text/html"
}
]
},

Feature Request: Output to file

It would be great to add CLI option to output to file instead of stdout.
Something similar to -O in wget to run it like prettyjson package.json -O pretty-package.yaml instead of prettyjson package.json > pretty-package.yaml

Keep Braces, Brackets

I'd love to see an option to keep braces and brackets, along with proper indenting, when rendering. The aim would be a colored output, but with content no different than JSON.stringify(data, null, 2), for example.

No color in nodejs anymore

Hi there,

Why is it that all of the sudden the colors are gone in the terminal printing from my nodejs app?

Anyone experiencing this?

Error when passing nothing

Should probably check that data is defined...

console.log(prettyjson.render())
  for (var names = originalGetOPNs(object),
                   ^
TypeError: Cannot convert undefined or null to object
    at getOwnPropertyNames (<anonymous>)
    at Function.getOwnPropertyNames (/Users/Vaughan/dev-vjpr/packages/jetbrains-project/node_modules/.registry.npmjs.org/private/0.1.8/node_modules/private/private.js:72:20)
    at Object.exports.getMaxIndexLength (/Users/Vaughan/dev-vjpr/packages/jetbrains-project/node_modules/.registry.npmjs.org/prettyjson/1.2.1/node_modules/prettyjson/lib/utils.js:16:10)
    at renderToArray (/Users/Vaughan/dev-vjpr/packages/jetbrains-project/node_modules/.registry.npmjs.org/prettyjson/1.2.1/node_modules/prettyjson/lib/prettyjson.js:141:52)
    at Object.render (/Users/Vaughan/dev-vjpr/packages/jetbrains-project/node_modules/.registry.npmjs.org/prettyjson/1.2.1/node_modules/prettyjson/lib/prettyjson.js:210:10)

Allow YAML input

So I can see my yaml files with color

cat myfile.yaml | prettyjson

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.