Code Monkey home page Code Monkey logo

fracturedjsonjs's Introduction

FracturedJsonJs

FracturedJson is a family of utilities that format JSON data in a way that's easy for humans to read, but fairly compact. Arrays and objects are written on single lines, as long as they're neither too long nor too complex. When several such lines are similar in structure, they're written with fields aligned like a table. Long arrays are written with multiple items per line across multiple lines.

This npm module is part of a family of FracturedJson tools.

Example

Here's a sample of output using nearly-default settings:

{
    "SimpleArray": [
        2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,  37,  41,  43,  47,  53,
        59,  61,  67,  71,  73,  79,  83,  89,  97, 101, 103, 107, 109, 113
    ],
    "ObjectColumnsArrayRows": {
        "Katherine": ["blue"      , "lightblue", "black"       ],
        "Logan"    : ["yellow"    , "blue"     , "black", "red"],
        "Erik"     : ["red"       , "purple"                   ],
        "Jean"     : ["lightgreen", "yellow"   , "black"       ]
    },
    "ArrayColumnsObjectRows": [
        { "type": "turret"   , "hp": 400, "loc": {"x": 47, "y":  -4}, "flags": "S"   },
        { "type": "assassin" , "hp":  80, "loc": {"x": 12, "y":   6}, "flags": "Q"   },
        { "type": "berserker", "hp": 150, "loc": {"x":  0, "y":   0}                 },
        { "type": "pittrap"  ,            "loc": {"x": 10, "y": -14}, "flags": "S,I" }
    ],
    "ComplexArray": [
        [19,  2],
        [ 3,  8],
        [14,  0],
        [ 9,  9],
        [ 9,  9],
        [ 0,  3],
        [10,  1],
        [ 9,  1],
        [ 9,  2],
        [ 6, 13],
        [18,  5],
        [ 4, 11],
        [12,  2]
    ]
}

If enabled in the settings, it can also handle JSON-with-comments (which isn't real JSON).

{
  /*
   * Multi-line comments
   * are fun!
   */
  "NumbersWithHex": [
      254 /*00FE*/,  1450 /*5AA*/ ,     0 /*0000*/, 36000 /*8CA0*/,    10 /*000A*/, 
      199 /*00C7*/, 15001 /*3A99*/,  6540 /*198C*/
  ], 
  /* Elements are keen */
  "Elements": [
    { /*Carbon*/   "Symbol": "C" , "Number":  6, "Isotopes": [11, 12, 13, 14] }, 
    { /*Oxygen*/   "Symbol": "O" , "Number":  8, "Isotopes": [16, 18, 17    ] }, 
    { /*Hydrogen*/ "Symbol": "H" , "Number":  1, "Isotopes": [ 1,  2,  3    ] }, 
    { /*Iron*/     "Symbol": "Fe", "Number": 26, "Isotopes": [56, 54, 57, 58] }  
    // Not a complete list...
  ], 

  "Beatles Songs": [
    "Taxman"        ,  // George
    "Hey Jude"      ,  // Paul  
    "Act Naturally" ,  // Ringo 
    "Ticket To Ride"   // John  
  ]
}

Install

npm i fracturedjsonjs

Usage

const { Formatter, CommentPolicy, FracturedJsonOptions, EolStyle } = require('fracturedjsonjs');

// For examples of the options, see
// https://github.com/j-brooke/FracturedJson/wiki/Options
const options = new FracturedJsonOptions();
options.MaxTotalLineLength = 80;
options.MaxInlineComplexity = 1;
options.JsonEolStyle = EolStyle.Crlf;

const formatter = new Formatter();
formatter.Options = options;

// Use Serialize to go from JavaScript data to JSON text.
const inputObj = [[1, 2, 3], [4, 16, 64]];
const textFromObj = formatter.Serialize(inputObj);

console.log("From inputObj:");
console.log(textFromObj);

// Comments aren't allowed by default, but they're easy to enable.
formatter.Options.CommentPolicy = CommentPolicy.Preserve;
formatter.Options.IndentSpaces = 2;

// Use Reformat to go from JSON text to JSON text.
const inputText = '{ "a": [1, 2, 3] /* <a */, "b": [null, 5] /* <b */ }';
const textFromText = formatter.Reformat(inputText);

console.log("From inputText:");
console.log(textFromText);

fracturedjsonjs's People

Contributors

chenxxzhe avatar j-brooke 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

Watchers

 avatar  avatar  avatar  avatar  avatar

fracturedjsonjs's Issues

Right align numbers in an array without changing the precision

Thanks for this excellent library! It really results in much better readable JSON.

I stumbled upon the feature that numbers in a long multiline array are right aligned and the precision of values is adjusted. This can be turned off with the option DontJustifyNumbers. I love the right formatting of numbers, that makes sense. However, changing the precision comes with a risk: formatted numbers like 4.0 can be changed into 4, 1e500 is changed into Infinity, and 1e-500 into 0, because JavaScript numbers can't handle that. This happens for example with the first three numbers in the following array:

[
  1e500, 1e-500, 4.0, 
  2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
  59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113
]

I would love to have the right formatting of numbers (it looks really neat!), but without the risk of changing the numbers. Is there a way to do that? Or are you open to introduce a new option for that or extend the option DontJustifyNumbers to have this "safe" variant?

Is there any plan to support full-width characters?

Hi.

This module is awesome!
I love to use this by VScode extension.

I met a issue when I format JSON data which is included Japanese characters.

Before JSON:

[
  {
     "field1": "foobar",
     "field2": "あいうえお",
     "field3": 1
  },
  {
     "field1": "foo",
     "field2": "あいうえ",
     "field3": 10
  },
  {
     "field1": "bara",
     "field2": "あいう",
     "field3": 100
  }
]

After JSON:

[
    { "field1": "foobar", "field2": "あいうえお", "field3":   1 },
    { "field1": "foo"   , "field2": "あいうえ" , "field3":  10 },
    { "field1": "bara"  , "field2": "あいう"  , "field3": 100 }
]

This issue may be caused by Unicode full-width characters.
There are some modules to solve it. (ex. https://www.npmjs.com/package/string-width)

Is there any plan to support full-width characters?

Generate formatted JS code as well as JSON

I have no idea if you'd be interested in work to also format output suitable for code generation, meaning mostly JSON without quoting property names unnecessarily.

If so, I will see if I can find time to create a PR for such.

The idea is to generate something like this:

    const myConfig = {
        SimpleArray: [
              2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,  37,  41,  43,  47,  53,
             59,  61,  67,  71,  73,  79,  83,  89,  97, 101, 103, 107, 109, 113
        ],
        ObjectColumnsArrayRows: {
            Katherine: [ "blue"      , "lightblue", "black"        ],
            Logan    : [ "yellow"    , "blue"     , "black", "red" ],
            Erik     : [ "red"       , "purple"                    ],
            Jean     : [ "lightgreen", "yellow"   , "black"        ]
        },
        ArrayColumnsObjectRows: [
            { type: "turret"   , hp: 400, loc: {x: 47, y: -4} , flags: "S"   },
            { type: "assassin" , hp:  80, loc: {x: 12, y: 6}  , flags: "Q"   },
            { type: "berserker", hp: 150, loc: {x: 0,  y: 0}                 },
            { type: "pittrap"  ,          loc: {x: 10, y: -14}, flags: "S,I" }
        ],
        ComplexArray: [
            [ 19,  2 ],
            [  3,  8 ],
            [ 14,  0 ],
            [  9,  9 ],
            [  9,  9 ],
            [  0,  3 ],
            [ 10,  1 ],
            [  9,  1 ],
            [  9,  2 ],
            [  6, 13 ],
            [ 18,  5 ],
            [  4, 11 ],
            [ 12,  2 ]
        ],
        "Of course some props will still": "need to be quoted"
    }

I'm doing a bit of code generation now and I would love to have cleaner output than I sometimes get with the code formatters. This looks like it would do the job well.

If you're interested, let me know. Any hints about where to start in the code would help. (I haven't looked at all yet; maybe it will be obvious.)

Float 0.0 converted to 0

Using this script:

const { Formatter, EolStyle } = require("fracturedjsonjs");
const fs = require('fs');

const argv = process.argv.slice(1);

let rawdata = fs.readFileSync(argv[1])
let jsObj = JSON.parse(rawdata);

const formatter = new Formatter();

formatter.alwaysExpandDepth = 0
formatter.maxInlineLength = 10000
formatter.maxInlineComplexity = 100
formatter.maxCompactArrayComplexity = 100

const jsonString = formatter.serialize(jsObj);
console.log(jsonString);

and this JSON:

{
    "AttackPlans": [
        {
            "TeamId": 1,
            "Spawns": [
                {
                    "Time": 0.0,
                    "UnitType": "Grunt",
                    "SpawnPointIndex": 0
                },
                {
                    "Time": 0.0,
                    "UnitType": "Grunt",
                    "SpawnPointIndex": 0
                },
                {
                    "Time": 0.0,
                    "UnitType": "Grunt",
                    "SpawnPointIndex": 0
                }
            ]
        }
    ],
    "DefensePlans": [
        {
            "TeamId": 2,
            "Placements": [
                {
                    "UnitType": "Archer",
                    "Position": [
                        41,
                        7
                    ]
                },
                {
                    "UnitType": "Pikeman",
                    "Position": [
                        40,
                        7
                    ]
                },
                {
                    "UnitType": "Barricade",
                    "Position": [
                        39,
                        7
                    ]
                }
            ]
        }
    ]
}

I get the following output:

{
    "AttackPlans" : [ { "TeamId": 1, "Spawns": [ {"Time": 0, "UnitType": "Grunt", "SpawnPointIndex": 0}, {"Time": 0, "UnitType": "Grunt", "SpawnPointIndex": 0}, {"Time": 0, "UnitType": "Grunt", "SpawnPointIndex": 0} ] } ],
    "DefensePlans": [ { "TeamId": 2, "Placements": [ { "UnitType": "Archer", "Position": [41, 7] }, { "UnitType": "Pikeman", "Position": [40, 7] }, { "UnitType": "Barricade", "Position": [39, 7] } ] }                    ]
}

Note that the Time parameter has been converted from a float to an int (0.0 to 0). Basically I am unable to reproduce the output from https://github.com/j-brooke/FracturedJson/wiki/Options (and not in browser either).

SimpleBracketPadding is ignored for table rows

In version 3.0.0, the setting SimpleBracketPadding=true is being ignored when formatting as a table.

Example:

    const input = "[[1, 2],[3, 4]]";
    const formatter = new Formatter();
    formatter.Options.MaxInlineComplexity = 1;
    formatter.Options.SimpleBracketPadding = true;
    let output = formatter.Reformat(input, 0);

Expected output:

[
    [ 1, 2 ], [ 3, 4 ]
]

Actual output:

[
    [1, 2], [3, 4]
]

Undefined values in object are not handled

By trying to serialize an object that contains undefined values the library will break:

const formatter = new Formatter()
formatter.serialize({ a: undefined })

will produce the following exception:

Uncaught TypeError: Cannot read properties of undefined (reading 'match')
    at stringToArray (/.../node_modules/eastasianwidth/eastasianwidth.js:273:17)
    at Object.eaw.length (/.../node_modules/eastasianwidth/eastasianwidth.js:277:20)
    at Formatter.StringWidthWithEastAsian [as _stringWidthFunc] (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:235:20)
    at Formatter.formatSimple (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:284:39)
    at Formatter.formatElement (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:271:34)
    at Formatter.formatObject (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:342:31)
    at Formatter.formatElement (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:269:34)
    at Formatter.serialize (/.../node_modules/fracturedjsonjs/dist/fracturedjson.js:221:42)

For now the workaround that I use is to do:

formatter.serialize(JSON.parse(JSON.stringify({ a: undefined })))

To remove undefined values from an object.

Escape sequences in property names are not preserved

Property names can be any valid JSON string, so they can have escape sequences like \n and \". FracturedJsonJs 2.0.0 is not properly preserving those escapes, sometimes producing invalid output.

Example -
input:

{
    "ab\ncd": [1,2,3],
    "wx\"yz": [4,16,64]
}

observed output:

{
    "ab
cd": [ 1,  2,  3 ],
    "wx"yz": [ 4, 16, 64 ]
}

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.