Skip to content

Instantly share code, notes, and snippets.

@missinglink
Last active April 22, 2024 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save missinglink/9ff8b6fe26bad1d88cdf19c041062856 to your computer and use it in GitHub Desktop.
Save missinglink/9ff8b6fe26bad1d88cdf19c041062856 to your computer and use it in GitHub Desktop.
Custom `JSON.stringify` replacer which provides the object path and depth
// decorator
function replacerWithPath (fn) {
let paths = new Map()
return function (key, value) {
let path = paths.get(this) || '$'
if (key) path += Array.isArray(this) ? `[${key}]` : `.${key}`
let v = fn(key, value, path)
if (v === Object(v)) paths.set(v, path)
return v
}
}
// custom replacer fn has access to the jpath
function replacer (key, value, path) {
console.log(path, key)
return value
}
// usage
console.log(
JSON.stringify(value, replacerWithPath(replacer), 2)
)
@missinglink
Copy link
Author

missinglink commented Apr 22, 2024

This works because this within the scope of the replacer called by JSON.stringify is bound to the parent JSON element, while the key and value arguments refer to the child element.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment