DEV Community

ehmicky
ehmicky

Posted on

⛑ JSON serialization should never fail.

safe-json-value is a JavaScript library to prevent JSON.serialize() from:

Example:

import safeJsonValue from 'safe-json-value'

const input = { one: true }
input.self = input

JSON.stringify(input) // Throws due to cycle
const { value, changes } = safeJsonValue(input)
JSON.stringify(value) // '{"one":true}"

console.log(changes) // List of changed properties
// [
//   {
//     path: ['self'],
//     oldValue: <ref *1> { one: true, self: [Circular *1] },
//     newValue: undefined,
//     reason: 'unsafeCycle'
//   }
// ]
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)