Coder Social home page Coder Social logo

lydell / json-stringify-pretty-compact Goto Github PK

View Code? Open in Web Editor NEW
250.0 6.0 31.0 366 KB

The best of both `JSON.stringify(obj)` and `JSON.stringify(obj, null, indent)`.

Home Page: https://lydell.github.io/json-stringify-pretty-compact/

License: MIT License

JavaScript 68.57% HTML 31.43%
json stringify

json-stringify-pretty-compact's Introduction

json-stringify-pretty-compact

The output of JSON.stringify comes in two flavors: compact and pretty. The former is usually too compact to be read by humans, while the latter sometimes is too spacious. This module trades performance for a compromise between the two. The result is a pretty compact string, where “pretty” means both “kind of” and “nice”.

{
  "bool": true,
  "short array": [1, 2, 3],
  "long array": [
    {"x": 1, "y": 2},
    {"x": 2, "y": 1},
    {"x": 1, "y": 1},
    {"x": 2, "y": 2}
  ]
}

While the “pretty” mode of JSON.stringify puts every item of arrays and objects on its own line, this module puts the whole array or object on a single line, unless the line becomes too long (the default maximum is 80 characters). Making arrays and objects multi-line is the only attempt made to enforce the maximum line length; if that doesn’t help then so be it.

Installation

npm install json-stringify-pretty-compact
import stringify from "json-stringify-pretty-compact";

Note: This is an ESM only package. (I haven’t written that gist, but it’s a great resource.)

If you need CommonJS, install version 3.0.0. You won’t be missing out on anything: This package is done. No more features will be added, and no bugs have been found in years.

Want a CLI? Check out avantgardnerio/json-stringify-pretty-compact-cli!

Web version? Check out the online demo!

stringify(obj, options = {})

It’s like JSON.stringify(obj, options.replacer, options.indent), except that objects and arrays are on one line if they fit (according to options.maxLength).

options:

  • indent: Defaults to 2. Works exactly like the third parameter of JSON.stringify.
  • maxLength: Defaults to 80. Lines will be tried to be kept at maximum this many characters long.
  • replacer: Defaults to undefined. Works exactly like the second parameter of JSON.stringify.

stringify(obj, {maxLength: 0, indent: indent}) gives the exact same result as JSON.stringify(obj, null, indent). (However, if you use a replacer, integer keys might be moved first.)

stringify(obj, {maxLength: Infinity}) gives the exact same result as JSON.stringify(obj), except that there are spaces after colons and commas.

Want more options? Check out @aitodotai/json-stringify-pretty-compact!

License

MIT.

json-stringify-pretty-compact's People

Contributors

dependabot[bot] avatar domoritz avatar g-rath avatar lydell avatar randallsquared 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

json-stringify-pretty-compact's Issues

String contents is being json formatted

Sorry to give such a poorly written use case. Maybe I can get this into a testcase in the future but I wanted to capture the issue before I forgot about it.

I ran into a case where the value of an object was a string that contained some valid json and it was formatted.

Notice the difference in the spacing in this portion of the comments string: {errors:insufficient_storage,status:507}

Here is a portion of the original input:

 {
    "_id": "58d421ee0cfbd700344e4c6c",
    "comments": "Could not instantiate with error -Service broker error: {+description\"=>Deployment creation failed - {errors:insufficient_storage,status:507}+ }-",
    "rating": 1,
    "criteria": "Payment",
    "offering": "Compose for RabbitMQ",
    "service": "Message Queue",
    "platform": "Bluemix",
    "author": "[email protected]",
    "type": "rating",
    "__v": 0,
    "date": "2017-03-16T00:00:00.000Z"
  },

Here is a portion of the resulting stringify output:

{
 "author": "",
 "date": "",
 "offerings": [
  {
   "old": [
    {"_id": "58d421ee0cfbd700344e4c6c", "comments": "Could not instantiate with error -Service broker error: {+description\"=>Deployment creation failed - {errors: insufficient_storage, status: 507}+ }-","rating":1,"criteria":"Payment","offering":"Compose for RabbitMQ","service":"Message Queue","platform":"Bluemix","author":"[email protected]","type":"rating","__v":0,"date":"2017-03-16T00: 00: 00.000Z"},
    {"_id": "58d421ee0cfbd700344e4c62", "comments": "Could not instantiate with error -Service broker error: {+description\"=>Deployment creation failed - {errors: insufficient_storage, status: 507}+ }-","rating":1,"criteria":"Security","offering":"Compose for RabbitMQ","service":"Message Queue","platform":"Bluemix","author":"[email protected]","type":"rating","__v":0,"date":"2017-03-16T00: 00: 00.000Z"},

TS typings

It would be awesome if you could provide Typescript typings for this module.

Matrix mode?

I found this lib after hitting an issue where Prettier does not format long arrays well (prettier/prettier#4210).

One user had a great suggestion:

// prettier-mode matrix
const userIds = [
  7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166,
  7234932843, 7234932978, 7234932436, 7234932687, 7234932269, 7234932573,
  7234932913, 7234932873, 7234932748, 7234932354, 7234932153, 7234932181,
  7234932947, 7234932563, 7234932324, 7234932952, 7234932885, 7234932911,
  7234932698, 7234932248, 7234932764, 7234932431, 7234932811, 7234932344,
  7234932855, 7234932430, 7234932396, 7234932981, 7234932594, 7234932131,
  7234932489, 7234932552, 7234932116, 7234932833, 7234932521, 7234932252,
  7234932503, 7234932540, 7234932893, 7234932736, 7234932969, 7234932145,
  7234932925, 7234932417, 7234932344, 7234932108, 7234932161, 7234932777,
  7234932971, 7234932159, 7234932158, 7234932908, 7234932511, 7234932876,
  7234932768, 7234932284, 7234932640, 7234932309, 7234932651, 7234932292,
  7234932898, 7234932284, 7234932201, 7234932506, 7234932654, 7234932840,
  7234932334, 7234932246, 7234932376, 7234932398, 7234932714, 7234932134,
  7234932435, 7234932181, 7234932980, 7234932594, 7234932396, 7234932100,
  7234932743, 7234932812, 7234932583, 7234932622, 7234932800, 7234932310,
  7234932111, 7234932537, 7234932751, 7234932920, 7234932872, 7234932700,
  7234932702, 7234932655, 7234932515, 7234932298
];

I tried to achieve that with your lib but line breaks right now seem to be all or nothing.

My input, pasted below, exceeds the line length so each array value gets it's own line. Might help the 40+ devs on that thread.

Also, a simple webpage with a textarea demo would be great, so if I just wanted to reformat 1 document or to kick the tires i didn't have to go through NPM and the whole shebang.

  stringify([
    "#440154",
    "#440256",
    "#450457",
    "#450559",
    "#46075a",
    "#46085c",
    "#460a5d",
    "#460b5e",
    "#470d60",
    "#470e61",
    "#471063",
    "#471164",
    "#471365",
    "#481467",
    "#481668",
    "#481769",
    "#48186a",
    "#481a6c",
    "#481b6d",
    "#481c6e",
    "#481d6f",
    "#481f70",
    "#482071",
    "#482173",
    "#482374",
    "#482475",
    "#482576",
    "#482677",
    "#482878",
    "#482979",
    "#472a7a",
    "#472c7a",
    "#472d7b",
    "#472e7c",
    "#472f7d",
    "#46307e",
    "#46327e",
    "#46337f",
    "#463480",
    "#453581",
    "#453781",
    "#453882",
    "#443983",
    "#443a83",
    "#443b84",
    "#433d84",
    "#433e85",
    "#423f85",
    "#424086",
    "#424186",
    "#414287",
    "#414487",
    "#404588",
    "#404688",
    "#3f4788",
    "#3f4889",
    "#3e4989",
    "#3e4a89",
    "#3e4c8a",
    "#3d4d8a",
    "#3d4e8a",
    "#3c4f8a",
    "#3c508b",
    "#3b518b",
    "#3b528b",
    "#3a538b",
    "#3a548c",
    "#39558c",
    "#39568c",
    "#38588c",
    "#38598c",
    "#375a8c",
    "#375b8d",
    "#365c8d",
    "#365d8d",
    "#355e8d",
    "#355f8d",
    "#34608d",
    "#34618d",
    "#33628d",
    "#33638d",
    "#32648e",
    "#32658e",
    "#31668e",
    "#31678e",
    "#31688e",
    "#30698e",
    "#306a8e",
    "#2f6b8e",
    "#2f6c8e",
    "#2e6d8e",
    "#2e6e8e",
    "#2e6f8e",
    "#2d708e",
    "#2d718e",
    "#2c718e",
    "#2c728e",
    "#2c738e",
    "#2b748e",
    "#2b758e",
    "#2a768e",
    "#2a778e",
    "#2a788e",
    "#29798e",
    "#297a8e",
    "#297b8e",
    "#287c8e",
    "#287d8e",
    "#277e8e",
    "#277f8e",
    "#27808e",
    "#26818e",
    "#26828e",
    "#26828e",
    "#25838e",
    "#25848e",
    "#25858e",
    "#24868e",
    "#24878e",
    "#23888e",
    "#23898e",
    "#238a8d",
    "#228b8d",
    "#228c8d",
    "#228d8d",
    "#218e8d",
    "#218f8d",
    "#21908d",
    "#21918c",
    "#20928c",
    "#20928c",
    "#20938c",
    "#1f948c",
    "#1f958b",
    "#1f968b",
    "#1f978b",
    "#1f988b",
    "#1f998a",
    "#1f9a8a",
    "#1e9b8a",
    "#1e9c89",
    "#1e9d89",
    "#1f9e89",
    "#1f9f88",
    "#1fa088",
    "#1fa188",
    "#1fa187",
    "#1fa287",
    "#20a386",
    "#20a486",
    "#21a585",
    "#21a685",
    "#22a785",
    "#22a884",
    "#23a983",
    "#24aa83",
    "#25ab82",
    "#25ac82",
    "#26ad81",
    "#27ad81",
    "#28ae80",
    "#29af7f",
    "#2ab07f",
    "#2cb17e",
    "#2db27d",
    "#2eb37c",
    "#2fb47c",
    "#31b57b",
    "#32b67a",
    "#34b679",
    "#35b779",
    "#37b878",
    "#38b977",
    "#3aba76",
    "#3bbb75",
    "#3dbc74",
    "#3fbc73",
    "#40bd72",
    "#42be71",
    "#44bf70",
    "#46c06f",
    "#48c16e",
    "#4ac16d",
    "#4cc26c",
    "#4ec36b",
    "#50c46a",
    "#52c569",
    "#54c568",
    "#56c667",
    "#58c765",
    "#5ac864",
    "#5cc863",
    "#5ec962",
    "#60ca60",
    "#63cb5f",
    "#65cb5e",
    "#67cc5c",
    "#69cd5b",
    "#6ccd5a",
    "#6ece58",
    "#70cf57",
    "#73d056",
    "#75d054",
    "#77d153",
    "#7ad151",
    "#7cd250",
    "#7fd34e",
    "#81d34d",
    "#84d44b",
    "#86d549",
    "#89d548",
    "#8bd646",
    "#8ed645",
    "#90d743",
    "#93d741",
    "#95d840",
    "#98d83e",
    "#9bd93c",
    "#9dd93b",
    "#a0da39",
    "#a2da37",
    "#a5db36",
    "#a8db34",
    "#aadc32",
    "#addc30",
    "#b0dd2f",
    "#b2dd2d",
    "#b5de2b",
    "#b8de29",
    "#bade28",
    "#bddf26",
    "#c0df25",
    "#c2df23",
    "#c5e021",
    "#c8e020",
    "#cae11f",
    "#cde11d",
    "#d0e11c",
    "#d2e21b",
    "#d5e21a",
    "#d8e219",
    "#dae319",
    "#dde318",
    "#dfe318",
    "#e2e418",
    "#e5e419",
    "#e7e419",
    "#eae51a",
    "#ece51b",
    "#efe51c",
    "#f1e51d",
    "#f4e61e",
    "#f6e620",
    "#f8e621",
    "#fbe723",
    "#fde725",
  ])

deterministic string results like json-stable-stringify

Is this module's output stable as json-stable-stringify ?

I have a requirement, where after serialising json document, the document should be pushed to git.
If keys order changes frequently, git's diff will become a mess.

Margins feature request.

There is a proposal to make an option that sets margins only for objects in which there is data.

For example:

{
	"data": {
		"object": {  },
		"array": [  ],
		"obj": { "bool": true }
	}
}

Become:

{
	"data": {
		"object": {},
		"array": [],
		"obj": { "bool": true }
	}
}

thanks

Hi

Just wanted to say thank you. I added your code to https://arkenfox.github.io/TZP/tzp.html, tweaked it a little to suit and added colors (to match Firefox dark theme dev console - it really makes some of the data so much more compact when testing/inspecting

all the clickable details/metrics etc popup an overlay which I populate with the relevant JSON

since it only runs on gecko browsers (Firefox 102 based or higher), here's a pic. I've credited and linked to this repo at the top, in the pic you can just see lydell on the top right under the overlay

thanks

Fields sort option

Hi @lydell, thank you for this brilliant solution, why didn't I searched for it so long?
I suggest a new option to make JSON files even more readable:
sort fields of each object by value max depth + value number of lines + by field name alphabetically,
so first will go primitive values, next will be flat objects/arrays, and more complex values will go later.
example source JSON prettified by a current version

{
  "data": {
    "items": {
      "properties": {
        "icon": {
          "properties": {
            "width": {"type": ["string"], "default": "16px"},
            "height": {"type": ["string"], "default": "16px"},
            "url": {
              "type": ["string"],
              "required": true,
              "description": "Icon url. data urls are supported.",
              "default": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23FFFFFF' d='M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z' /%3E%3C/svg%3E"
            }
          },
          "description": "The name from collection or an object",
          "type": ["string", "object"],
          "default":"" // is it 'default' for 'icon' or 'properties' or 'items'?
        }
      }
    }
  },
  "style":{"CSS": ""},
  "id": null
}

after sorting:

{
  "id": null, // depth 0 (<1)
  "style":{ "CSS": "" }, // depth 1 (<7)
  "data": { // depth 7
    "items": {
      "properties": {
        "icon": {
          "default":"", // depth 0 ('def'<'des')
          "description": "The icon name from icons collection or an icon object", // depth (0<1)
          "type": ["string", "object"], // depth 1 (<3)
          "properties": { // depth 3
            "height": { "default": "16px", "type": ["string"] }, // depth 2, 1 line, ('h'<w)
            "width": { "default": "16px", "type": ["string"] }, // depth 2, 1 line, (< 6 lines)
            "url": { // depth 2, 6 lines
              "default": "data:image/svg+xml, ....", // depth 0 ('def'<'des')
              "description": "Icon url. data urls are supported.", // depth 0 ('d'<'r')
              "required": true, // depth 0 (<1)
              "type": ["string"] // depth 1
            }
          }
        }
      }
    }
  }
}

Main idea to see the simplest values first,
because it's difficult to find simple value at specific nesting level, if it goes after complex object
and from the other side - it's difficult to say who is a owner of such field.

Yes I know someone will not be happy with changing the order of the fields, that's why it's optional.
But technically object's fields order is not guaranteed in the javascript, and developers should not rely on the fields order, so no real rule will be broken.

npmjs package page doesn't show readme

At https://www.npmjs.com/package/json-stringify-pretty-compact, it says there is no readme. This is because the published package does not include README.md:

$ tar tvf $(npm pack json-stringify-pretty-compact)
-rw-rw-r--  0 1000   1000      698 Sep  8  2016 package/package.json
-rw-rw-r--  0 1000   1000     1085 Sep  8  2016 package/LICENSE
-rw-rw-r--  0 1000   1000     2490 Sep  8  2016 package/index.js
-rw-rw-r--  0 1000   1000      341 Sep  8  2016 package/CHANGELOG.md

According to https://github.com/npm/registry/issues/120#issuecomment-276157329, old versions of npm didn't include README.md. If you upgrade your npm version, and publish a patch release of this module, the readme should appear on npmjs.com.


(issue markdown adapted from domenic/opener#24)

Online convertor

Is there an online version of this tool?
E.g. a simple page hosted through github pages?

Support a way to adjust the algorithm based on the object

I want some objects to be on a single line regardless of their length.

This is so I can more easily deal with the json file in an editor (search for multiple keys and values with regular expressions and make editing changes)

This is what I was thinking for the implementation

Pass a callback function that would take as a parameter the current object being stringify'ed would work in my case: function(obj)

There is a more complicated call back mechanism defined here: https://www.npmjs.com/package/pretty-json-stringify This is more then I need, but might add some generality. function(object, level, key)

It isn't clear to me what context would be generally useful for the callback. I think an array representing the path to the object's parent would be helpful

{ a: {b: {c: {d: [ "e", {f: "g"}]}}})

So when callback({f: "g"}) is being handled the parent would be:
["a", "b", "c", "d", 1]

maxLength failed

I have a description field in my json so the length can get a bit long. So I set maxLength to 1000 just to be safe but running stringify produces output that is just one line (not prettified in any way). I set maxLength to 500 and it worked well. Is there an upper limit on maxLength?

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.