Git Product home page Git Product logo

json.prune's Introduction

JSON.prune

Chat on Miaou Chat on Miaou

JSON.prune is a pruning JSON.stringify for the very specific cases where you need to stringify big or recursive javascript objects and don't really need the result to be complete.

var json = JSON.stringify(window); // fails
var json = JSON.prune(window); // builds a JSON valid string from a pruned version of the
                               // recursive, deep, and not totally accessible window object
var prunedWindow = JSON.parse(JSON.prune(window)); // builds a lighter acyclic version of window

JSON.prune also lets you, in case of need, stringify inherited and/or non enumerable properties.

JSON.prune(window.location, {inheritedProperties:true}); // without inherited properties, FireFox and IE only show an empty object

JSON.prune.log is a proxy over console.log deep cloning the objects (using JSON.prune) before logging them, in order to avoid the delay problem encountered on non primitive objects logging.

You should not use it frequently, only when you really need to see the objects how they were at logging time.

// make sure someObject is logged as it was at logging time
JSON.prune.log(someObject);

Project/Test page

dystroy.org/JSON.prune

Include it in a page

<script src=http://dystroy.org/JSON.prune/JSON.prune.js></script>

Use it with CommonJS or in node

var prune = require('json-prune');
var json = prune(obj);

Discussions

JavaScript room on Miaou

Customization: replace the "-pruned-" placeholder

Here's how are handled by default by JSON.prune the special values needing pruning:

Value Default
undefined Key and value are ommited (same as JSON.stringify)
function Key and value are ommited (same as JSON.stringify)
already written or too deep object (cycle prevention) The "-pruned-" string
array with too many elements Truncation: JSON.prune applied to only the start of the array

By specifiying a replacer or a prunedString in JSON.prune options, you can customize those prunings.

The replacer function takes 3 arguments:

  • the value to replace
  • the default replacement value
  • a boolean indicating whether the replacement is due to a cycle detection

Returning undefined makes JSON.prune ommit the property (name and value).

The default value makes it easy to just specify the specific behavior you want instead of implementing the whole standard replacement.

Example 1: Use an object instead of a string as pruning mark

var json = JSON.prune(obj, {prunedString: '{}' });

Note: if you want a string to be inserted, don't forget the double quotes, as in '"-pruned-"'.

Example 2: Silent Pruning

If you want the pruned properties to just be ommited, pass undefined as prunedString:

var obj = {a:3};
obj.self = obj;
var json = JSON.prune(obj);
console.log(json); // logs {"a":3,"self":"-pruned-"}
json = JSON.prune(obj, {prunedString: undefined });
console.log(json); // logs {"a":3}

Note: You get the same behavior with

json = JSON.prune(obj, {replacer: function(){}});

Example 3: Verbose Pruning

var options = {replacer:function(value, defaultValue, circular){
	if (circular) return '"-circular-"';
	if (value === undefined) return '"-undefined-"';
	if (Array.isArray(value)) return '"-array('+value.length+')-"';
	return defaultValue;
}};
var json = JSON.prune(obj, options);

Example 4: Function "serialization"

var options = {replacer:function(value, defaultValue){
	if (typeof value === "function") return JSON.stringify(value.toString());
	return defaultValue;
}};
var json = JSON.prune(obj, options);

Example 5: Array truncation mark

The default behavior on big arrays is to silently write only the first elements. It's possible with a replacer to add a string as last element:

var obj = {arr: Array.apply(0,Array(100)).map(function(_,i){ return i+1 })}
function replacer(value, defaultValue){
	if (Array.isArray(value)) return defaultValue.replace(/]$/, ',"-truncated-"]');
	return defaultValue;
}
var json = (asPrunedJSON(obj, {arrayMaxLength:5, replacer});

This produces

{"arr":[1,2,3,4,5,"-truncated-"]}

License

MIT

json.prune's People

Contributors

canop 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

json.prune's Issues

functions

For example, if you visit this page:

http://youtube.com/watch?v=qwspCgEUj64

Request:

yt.player.Application

Response:

Object { create: f9.create(), createWebComponent: f9.B() }

However pruned request:

JSON.prune(yt.player.Application)

Gives empty response:

"{}"

Is it possible to convert depth-first to breadth-first approach?

Hi Canop,
Thanks for the library. It helps me too much.

Currently, I came across this bug/feature. If you have an object referenced by a key inside an object which is in an array, it always assigns the following elements as -pruned-.

To clarify, let me explain it by example

var foo = {...};

var bar = 
[
  {
    a: 1, 
    b: foo
  },
  foo
];

JSON.prune(bar)

will yield
[{ a:1, b:{...} }, '-pruned-']

however, I expect it to be
[{a:1, b:'-pruned-', {...}]

It goes deeper as much as possible and goes top checks if the current element is found before. This occurs because the algorithm uses depth-first and what I need is to use breadth-first algorithm.

Would you mind to add this algorithm too or point me the right direction as the code seemed to me a bit complicated so I could find my own way.

License

Hi @Canop,
I think JSON.prune is a good library.
So it would be better to have an OSS license with this.
Best regards.

please support regexp

Thank you for sharing! Could you please support regexps?

JSON.prune({regexp: /abc123/});
"{"regexp":{}}"

expecting value same as from /abc123/.toString()

JSON.prune({regexp: /abc123/});
"{"regexp":"/abc123/"}"

Even better if you support also keyed collections, I mostly use maps

JSON.prune({map: new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
])});
"{"map":{}}"

can be stringified by

let myMap = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);
JSON.stringify(myMap, (key, value) => (value instanceof Map ? [...value] : value));
"[[1,"one"],[2,"two"],[3,"three"]]"

Many thanks :)

Doubt about license

I have a question about this library license. My question is about the package.json file, I've notice there's a license type named ISC that is different from what is displayed on your github page.
Which license is valid for this project of yours?
PS: I want use this lib in my commercial project, this is why I asking the license type.
Thank you.

support getters/setters

class MyClass {
	get value() {
		return "wow"
	}
};

const myClass = new MyClass();

console.log(JSON.prune(myClass)); // empty object {}

Common JS & NPM

Hi, thank you for this piece of code :)
It just helps me a lot 5 minutes ago.

I was wondering if it was possible to make this a commonJS module and publish it to NPM?

so we'll be able to make something like

var prune  = require('json-prune');

prune(obj);

Thanks again!

support for indentation?

Standerted JSON.stringify allows an argument for \t and \n for indentation purposes as follows:


JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'

JSON.prune supports it as well?

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.