Product
Introducing Java Support in Socket
We're excited to announce that Socket now supports the Java programming language.
The devalue npm package is used for serializing complex JavaScript data structures into a string form that can be evaluated to produce an equivalent structure. This is particularly useful for cases where JSON.stringify() is not sufficient, such as when dealing with circular references, Dates, RegExps, Maps, Sets, or functions. It's designed to handle cases that JSON struggles with, making it a powerful tool for certain serialization needs.
Serializing and deserializing complex objects
This feature demonstrates how devalue can serialize a complex object into a string and then deserialize it back into an object. Unlike JSON.stringify, devalue can handle circular references and other complex types not supported by JSON.
"const devalue = require('devalue');\nconst obj = { foo: 'bar', baz: { qux: 'quux' } };\nconst serialized = devalue(obj);\nconsole.log(serialized); // Output: '{foo:\"bar\",baz:{qux:\"quux\"}}'\neval('var restored = ' + serialized);\nconsole.log(restored); // Output: { foo: 'bar', baz: { qux: 'quux' } }"
Handling circular references
This example shows devalue's ability to handle circular references within objects, which JSON.stringify cannot do without throwing an error.
"const devalue = require('devalue');\nconst obj = {};\nobj.self = obj;\nconst serialized = devalue(obj);\nconsole.log(serialized); // Output: 'var x={};x.self=x;x'\neval('var restored = ' + serialized);\nconsole.log(restored.self === restored); // Output: true"
Serializing special types (Date, RegExp, Map, Set)
This feature highlights devalue's capability to serialize JavaScript's special object types like Date, RegExp, Map, and Set, which are not natively supported by JSON.stringify.
"const devalue = require('devalue');\nconst obj = {\n date: new Date(),\n regex: /test/i,\n map: new Map([['key', 'value']]),\n set: new Set([1, 2, 3])\n};\nconst serialized = devalue(obj);\nconsole.log(serialized); // Output includes serialized forms of Date, RegExp, Map, and Set"
Flatted is a package similar to devalue that can serialize and deserialize JavaScript objects with circular references using a flat structure. Unlike devalue, Flatted uses a JSON-compatible format and focuses specifically on circular data structures.
Serialize-javascript is another package that offers serialization of JavaScript objects into a string, including regular expressions, dates, and functions. It is similar to devalue but does not handle circular references as gracefully.
Like JSON.stringify
, but handles
obj.self = obj
)[value, value]
)undefined
, Infinity
, NaN
, -0
Map
and Set
BigInt
ArrayBuffer
and Typed ArraysTry it out here.
There are two ways to use devalue
:
uneval
This function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like eval
in reverse:
import * as devalue from 'devalue';
let obj = { message: 'hello' };
devalue.uneval(obj); // '{message:"hello"}'
obj.self = obj;
devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'
Use uneval
when you want the most compact possible output and don't want to include any code for parsing the serialized value.
stringify
and parse
These two functions are analogous to JSON.stringify
and JSON.parse
:
import * as devalue from 'devalue';
let obj = { message: 'hello' };
let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
devalue.parse(stringified); // { message: 'hello' }
obj.self = obj;
stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
devalue.parse(stringified); // { message: 'hello', self: [Circular] }
Use stringify
and parse
when evaluating JavaScript isn't an option.
unflatten
In the case where devalued data is one part of a larger JSON string, unflatten
allows you to revive just the bit you need:
import * as devalue from 'devalue';
const json = `{
"type": "data",
"data": ${devalue.stringify(data)}
}`;
const data = devalue.unflatten(JSON.parse(json).data);
You can serialize and deserialize custom types by passing a second argument to stringify
containing an object of types and their reducers, and a second argument to parse
or unflatten
containing an object of types and their revivers:
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
const stringified = devalue.stringify(new Vector(30, 40), {
Vector: (value) => value instanceof Vector && [value.x, value.y]
});
console.log(stringified); // [["Vector",1],[2,3],30,40]
const vector = devalue.parse(stringified, {
Vector: ([x, y]) => new Vector(x, y)
});
console.log(vector.magnitude()); // 50
If a function passed to stringify
returns a truthy value, it's treated as a match.
You can also use custom types with uneval
by specifying a custom replacer:
devalue.uneval(vector, (value, uneval) => {
if (value instanceof Vector) {
return `new Vector(${value.x},${value.y})`;
}
}); // `new Vector(30,40)`
Note that any variables referenced in the resulting JavaScript (like Vector
in the example above) must be in scope when it runs.
If uneval
or stringify
encounters a function or a non-POJO that isn't handled by a custom replacer/reducer, it will throw an error. You can find where in the input data the offending value lives by inspecting error.path
:
try {
const map = new Map();
map.set('key', function invalid() {});
uneval({
object: {
array: [map]
}
});
} catch (e) {
console.log(e.path); // '.object.array[0].get("key")'
}
Say you're server-rendering a page and want to serialize some state, which could include user input. JSON.stringify
doesn't protect against XSS attacks:
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
Which would result in this:
<script>
// NEVER DO THIS
var preloaded = {"userinput":"
</script>
<script src="https://evil.com/mwahaha.js">
"};
</script>
Using uneval
or stringify
, we're protected against that attack:
const template = `
<script>
var preloaded = ${uneval(state)};
</script>`;
<script>
var preloaded = {
userinput:
"\\u003C\\u002Fscript\\u003E\\u003Cscript src='https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js'\\u003E"
};
</script>
This, along with the fact that uneval
and stringify
bail on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by uneval
can be safely deserialized with eval
or new Function
:
const value = (0, eval)('(' + str + ')');
While uneval
prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, you should not send user data from client to server using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed uneval
would have access to your system.
When using eval
, ensure that you call it indirectly so that the evaluated code doesn't have access to the surrounding scope:
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
Using new Function(code)
is akin to using indirect eval.
stringify
/parse
approach in devalue
was inspired by arson
FAQs
Gets the job done when JSON.stringify can't
We found that devalue demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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.
Product
We're excited to announce that Socket now supports the Java programming language.
Security News
Socket detected a malicious Python package impersonating a popular browser cookie library to steal passwords, screenshots, webcam images, and Discord tokens.
Security News
Deno 2.0 is now available with enhanced package management, full Node.js and npm compatibility, improved performance, and support for major JavaScript frameworks.