Coder Social home page Coder Social logo

json-colorizer's Introduction

JSON Colorizer

Logo

A library for colorizing JSON strings

This package is a simple console syntax highlighter for JSON.

Installation

npm install --save json-colorizer

Usage

const { colorize } = require('json-colorizer');
console.log(colorize({ "foo": "bar" }));

You can also pass a JavaScript object to the colorize function:

const { colorize } = require('json-colorizer');
console.log(colorize({
  foo: 'bar',
  baz: 42
}));

Pretty-printing output

By default, the output JSON will be pretty-printed with an indentation of 2 spaces. You can adjust this by passing the indent option.

const { colorize } = require('json-colorizer');
console.log(colorize({
  foo: 'bar',
  baz: 42
}, { indent: 4 }));

Customizing the colors

You can override any of the colors used for token types by providing a colors option. This should map token types to the names of color functions. These color functions are contained in the color object exported by the library.

const { colorize, color } = require('json-colorizer');

console.log(colorize({ foo: 'bar' }, {
  colors: {
    StringLiteral: color.red
  }
}));

The list of valid token types and color functions are listed below.

Token types

  • Brace: curly braces ({, })
  • Bracket: square brackets ([, ])
  • Colon: colon character (:)
  • Comma: comma character (,)
  • StringKey: the key in a key/value pair
  • NumberLiteral: a number value
  • StringLiteral: a string value
  • BooleanLiteral: a boolean literal (true, false)
  • NullLiteral: the literal null value

Color functions in the color object

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • gray

json-colorizer's People

Contributors

gusnips avatar joeattardi avatar kevinpollet avatar rexxars avatar rknoll avatar wmgdevelop 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

json-colorizer's Issues

Allowing giving specific colors to certain JSON object keys/values

The basic idea is to add an ability that lets you give specific colors to specific keys for any JSON object that you happen to colorize. For example you can do something like

console.log(colorize({ "uri": "localhost:3000", "status":404}, {
  colors: {
    JSON_OBJECT_CUSTOM: function (key, value, currentJsonObject) {
      if (key === 'status' && currentJsonObject.hasOwnProperty('uri')) {
          if (value.toString.startsWith('2')) {
             return 'green';
          } else if (value.toString.startsWith('3') {
             return 'orange';
          } else if (value.toString.startsWith('4') {
             return 'red';
          } else if (value.toString.startsWith('5') {
             return 'red';
          }
          return null; // If we return null then we just use original color.
      }
    };
  }
}));

Would you be open to such functionality or is this considered scope creep?

2.1.0 Failed for WHITESPACE token type

const colorKey = colors[token.type] || defaultColors[token.type];
const colorFn = colorKey[0] === '#' ? chalk.hex(colorKey) : get(chalk, colorKey);

If I didn't provide customized colors options here, colorKeys should be undefined for WHITESPACE token type and then colorKey[0] fails naturally with TypeError: Cannot read property '0' of undefined.

Cannot find module './lexer'

Hi!

I'm unable to upgrade to 3.0.0. The following error occurs when trying to load json-colorizer:

[web] node:internal/modules/cjs/loader:1147
[web]   throw err;
[web]   ^
[web]
[web] Error: Cannot find module './lexer'
[web] Require stack:
[web] - /Users/jbpros/Projects/acw/node_modules/json-colorizer/dist/index.js
[web] - /Users/jbpros/Projects/acw/dist/main.js
[web]     at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
[web]     at Module._load (node:internal/modules/cjs/loader:985:27)
[web]     at Module.require (node:internal/modules/cjs/loader:1235:19)
[web]     at require (node:internal/modules/helpers:176:18)
[web]     at Object.<anonymous> (/Users/jbpros/Projects/acw/node_modules/json-colorizer/dist/index.js:27:17)
[web]     at Module._compile (node:internal/modules/cjs/loader:1376:14)
[web]     at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
[web]     at Module.load (node:internal/modules/cjs/loader:1207:32)
[web]     at Module._load (node:internal/modules/cjs/loader:1023:12)
[web]     at Module.require (node:internal/modules/cjs/loader:1235:19) {
[web]   code: 'MODULE_NOT_FOUND',
[web]   requireStack: [
[web]     '/Users/jbpros/Projects/acw/node_modules/json-colorizer/dist/index.js',
[web]     '/Users/jbpros/Projects/acw/dist/main.js'
[web]   ]
[web] }

Indeed, there is no lexer.js file in dist/, only index.js.

Thank you for building exactly what I needed

You've built exactly what I needed, and saved me a bunch of effort.

I'm writing a command line tool that outputs JSON, and I've been wanting to add syntax-highlighted color output to it for a while.

In December 2015, nothing like json-colorizer existed, so I started writing one (with the same name, even). My efforts were blocked on a feature to preserve whitespace in node-json-tokenizer, so I dropped it for a while.

Thank you! ๐Ÿ™‡โ€โ™‚๏ธ

Static

Hi, so I was wondering, for a project I'm doing for fun with C# Blazor I don't have NPM but I still want to use this, can you add a guide how to?

Colorize without pretty printing?

It would be really great if it were possible to colorize JSON without also automatically pretty-printing it with indents and multiple lines.

Fails to tokenize double-encoded JSON

This currently fails, ending up in an infinite loop:

lexer.getTokens('{"type":"blob","data":"{\"x\":1,\"y\":\"2\"}"}')
lexer.getTokens(JSON.stringify({type: 'blob', data: JSON.stringify({x: 1, y: '2'})}))

Converts null fields in to fields of type Boolean & comma is getting trimmed.

If the Input Json String has some null fields. Then those null fields are getting converted into boolean fields & comma are getting trimmed which makes it invalid JSON.

Please check the below code.
JSON path to check -> integration -> serviceData -> productDefinitions -> IS -> landscapeRegistry -> type

const colorize = require('json-colorizer');

var text = '{"integration": {"message": {"code": 0,"description": "Success"},"serviceData": {"dateCreated": 1556518628526,"createdID": "163df9fc4f1b4946a3e1ac378b45a20b","dateModified": 1556589601769,"modifiedID": "3","description": "sample solution","solutionType": 2,"active": false,"dateActivated": 1556518628526,"productDefinitions": {"IS": [{"name": "IS","version": "10.4","replicaCount": 1,"statefulCluster": false,"productType": "IS","dependencies": ["UM", "DB"],"labels": {"app": "IS","stagename": "Development","product": "is","solution": "Solution3","stage": "stage00","subDomain": "setup","tenantid": "1737250844"},"image": {"tag": "10.4.19.04"},"resources": {"limits": {"cpu": "1","memory": "2"}},"env": {"packages": ["packages.WmCloudStreams.enabled=true", "packages.WmJDBCAdapter.enabled=true"]},"extraParameters": {"cordinates": {"row": 5,"column": 3}},"landscapeRegistry": {"name": "IS","solutionName": "Solution3","stage": "stage00","type": null,"registryRoot": ".","registryNamespacesRoot": "."},"higherVersions": []}],"UNIVERSALMESSAGING": [{"name": "UM","version": "10.4","replicaCount": 1,"statefulCluster": false,"productType": "UNIVERSALMESSAGING","labels": {"app": "UM","stagename": "Development","product": "um","solution": "Solution3","stage": "stage00","subDomain": "setup","tenantid": "1737250844"},"image": {"tag": "10.4.19.04"},"resources": {"limits": {"cpu": "1","memory": "2"}},"env": {"packages": []},"extraParameters": {"cordinates": {"row": 5,"column": 11}},"landscapeRegistry": {"name": "UM","solutionName": "Solution3","stage": "stage00","type": null,"registryRoot": ".","registryNamespacesRoot": "."},"higherVersions": []}]},"stage": "stage00","solutionName": "Solution3"}}}';

console.log(colorize(text));

Specifying colors example has SyntaxError

SyntaxError: missing ) after argument list

It seems you missed the closing )

var colorize = require('json-colorizer');
var chalk = require('chalk')
console.log(colorize({ "foo": "bar" }, {
  colors: {
    STRING_KEY: chalk.green
  }
});

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.