Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
safe-json-stringify
Advanced tools
The safe-json-stringify package is designed to safely stringify JavaScript objects into JSON format, even when they contain circular references. This package ensures that the JSON.stringify function does not throw errors when encountering such references, making it useful for logging and debugging complex objects.
Safe Stringification
This feature allows you to safely stringify objects that contain circular references. The circular references are replaced with a placeholder string '[Circular]'.
const safeJsonStringify = require('safe-json-stringify');
const obj = { name: 'Alice' };
obj.self = obj;
const jsonString = safeJsonStringify(obj);
console.log(jsonString); // Output: {"name":"Alice","self":"[Circular]"}
Custom Replacer Function
This feature allows you to pass a custom replacer function to filter or modify the values during the stringification process. In this example, the replacer function removes any numeric values from the resulting JSON string.
const safeJsonStringify = require('safe-json-stringify');
const obj = { name: 'Alice', age: 30 };
const replacer = (key, value) => (typeof value === 'number' ? undefined : value);
const jsonString = safeJsonStringify(obj, replacer);
console.log(jsonString); // Output: {"name":"Alice"}
Custom Indentation
This feature allows you to specify a custom indentation level for the resulting JSON string, making it more readable. In this example, the JSON string is formatted with an indentation of 2 spaces.
const safeJsonStringify = require('safe-json-stringify');
const obj = { name: 'Alice', age: 30 };
const jsonString = safeJsonStringify(obj, null, 2);
console.log(jsonString); // Output: {
"name": "Alice",
"age": 30
}
The circular-json package provides similar functionality by allowing the stringification of objects with circular references. It replaces circular references with a placeholder and can also parse the resulting JSON string back into an object. However, it is no longer maintained and has been deprecated in favor of flatted.
The flatted package is a modern alternative to circular-json. It provides methods to stringify and parse objects with circular references by using a special JSON format. Flatted is actively maintained and offers better performance and smaller output size compared to safe-json-stringify.
The json-stringify-safe package is another alternative that handles circular references by replacing them with a placeholder string. It is similar to safe-json-stringify but does not offer as many customization options, such as custom replacer functions or indentation levels.
A wrapper for JSON.stringify
that handles circular references and prevents defined getters from throwing errors.
Circular references are handled by returning [Circular]
when a circular reference is spotted.
Defined getters that throw errors are handled by returning [Throws]
.
Install it using NPM
npm install safe-json-stringify
And require it into your Node project.
const safeJsonStringify = require('safe-json-stringify');
const data = {foo: 'bar'}
console.log(safeJsonStringify(data));
All the parameters of JSON.stringify
are accepted, try e.g. the following for a nicely formatted output:
console.log(safeJsonStringify(data, null, 2));
An ensureProperties
function is exposed too, which returns a safe object without the stringify step. Usage: safeJsonStringify.ensureProperties(data);
.
The stringify
function on the JavaScript JSON object will take any data and return a string representation of said data. If this data contains an object literal it will attempt to return the values of any enumerable property set on this object. This can be dangerous because JavaScript supports a couple of ways to define property getters on objects.
The old, non-standard, and now deprecated Object.prototype.__defineGetter__()
will define a named property which value is the return of a given function.
// Never ever do this in your code. Please.
var obj = {};
obj.__defineGetter__('foo', function() { return 'bar'; });
JSON.stringify(obj); // {"foo":"bar"}
This is kinda bad because we could make that function throw an error.
// Never ever do this in your code. Please.
var obj = {};
obj.__defineGetter__('foo', function() { throw new Error('ouch!'); });
JSON.stringify(obj); // error thrown
This property is created as an enumerable on the object, so the object from the previous example would make any function that iterates choke and throw an error. This is bad because one would never expect a simple property get to throw an error and bring down a system.
JSON.stringify
will blindly trust any object property, and will throw an error if it hits a defined property that throws an error. This could potentially take down your program.
The slightly better Object.defineProperty()
does the same thing, but has the common courtesy to not define the getter as enumerable--that is per default. The following example would bring us in the same situation as with __defineGetter__
.
// Never ever do this in your code. Please.
var obj = {};
Object.defineProperty(obj, 'foo', {
get: function() { throw new Error('ouch!'); },
enumerable: true // enumerable is false by default
});
JSON.stringify(obj); // error thrown
So, we can not trust any of them. One could argue that they should never be used, and we can, and should, apply that principle to our own software, but we cannot trust code from third-party modules. If data from third-party modules are to be stringified by JSON we should take these situations into considerations. This module attempt to do that by spotting defined getters and return "[Throws]" if said getter throws an error.
var safeJsonStringify = require('safe-json-stringify');
// Never ever do this in your code. Please.
var obj = {};
Object.defineProperty(obj, 'foo', {
get: function() { throw new Error('ouch!'); },
enumerable: true
});
safeJsonStringify(obj); // '{"foo":"[Throws]"}'
And it attempts to handle circular references too. It returns "[Circular]" if it spots one.
The MIT License (MIT)
Copyright (c) 2014-2017 Debitoor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Prevent defined property getters from throwing errors
The npm package safe-json-stringify receives a total of 2,133,062 weekly downloads. As such, safe-json-stringify popularity was classified as popular.
We found that safe-json-stringify demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 10 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.