CKTIS / JavaScript
JSON graph references and path escaping
Preserve shared objects and cycles in JSON text with explicit `$ref` markers and paths that distinguish characters in keys from path separators.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
Application-defined JSON graph marker: {"$ref":"<path>"}
Root path: "". Child path: parentPath + "/" + escapeToken(keyOrIndex).
escapeToken(token): replace ~ with ~0, then / with ~1.
To read a path as segments, treat "" as zero segments. For any other path, require a leading /, remove exactly that first /, then split the remainder at /, keeping empty segments. The path / has one empty segment. In each segment, replace ~1 with /, then ~0 with ~.JSON graph references and path escaping let an application represent object links in text. Plain JSON records a tree of values, not object identity. With default JSON.stringify(), a shared object with no cycle is written separately at each occurrence. JSON.parse() creates distinct objects from those copies. If serialization encounters a cycle, JSON.stringify() throws TypeError.
In this application convention, a WeakMap records an object's first path before visiting its children. A later encounter with the same object emits {"$ref":"<path>"}. This one-field object with a string value is reserved for references; JSON.parse() does not resolve it by itself.
The JSON Pointer-style path "" denotes the root; / denotes its property with an empty key. Each segment is an object key or a zero-based array index. Before joining segments with /, replace ~ with ~0, then / with ~1. The key a/~1 gives /a~1~01. When reading a path, treat "" as zero segments. Every nonempty path must start with /: remove only that first /, then split the remainder at /, keeping empty segments. Thus / has one empty segment. In each segment, replace ~1 with /, then ~0 with ~. This is separate from JSON string escaping and URI percent-encoding.
After parsing, index the actual objects and arrays first, then replace markers with their targets. This also handles forward references. For untrusted data, validate the format, cap size and depth, and reject invalid paths and missing targets. Do not use eval() or traverse prototype chains.
If you need a copy rather than text, structuredClone() preserves cycles and sharing for supported values. It is a web platform API, not a JSON method; availability varies by runtime.
Examples
{
const childPath = (path, key) =>
path + '/' + String(key).replace(/~/g, '~0').replace(/\//g, '~1');
const shared = { count: 1 };
const graph = { 'a/~1': shared, alias: shared };
graph.self = graph;
const seen = new WeakMap();
function encode(value, path = '') {
if (value === null || typeof value !== 'object') return value;
if (seen.has(value)) return { $ref: seen.get(value) };
seen.set(value, path);
if (Array.isArray(value)) {
return value.map((item, index) => encode(item, childPath(path, index)));
}
return Object.fromEntries(Object.entries(value).map(([key, item]) =>
[key, encode(item, childPath(path, key))]));
}
const text = JSON.stringify(encode(graph));
const restored = JSON.parse(text);
const nodes = new Map();
const links = [];
function index(node, path = '') {
nodes.set(path, node);
for (const [key, item] of Object.entries(node)) {
if (item === null || typeof item !== 'object') continue;
const keys = Object.keys(item);
if (!Array.isArray(item) && keys.length === 1 && keys[0] === '$ref' &&
typeof item.$ref === 'string') {
links.push([node, key, item.$ref]);
} else {
index(item, childPath(path, key));
}
}
}
index(restored);
for (const [owner, key, path] of links) {
if (!nodes.has(path)) throw new Error('Invalid reference path');
owner[key] = nodes.get(path);
}
console.log(text);
console.log(restored.alias === restored['a/~1']);
console.log(restored.self === restored);
}Result
{"a/~1":{"count":1},"alias":{"$ref":"/a~1~01"},"self":{"$ref":""}}
true
trueThe demo uses trusted data: plain objects, dense arrays, and JSON-representable primitive values. The decoder matches complete escaped paths in a `Map`, so it does not need to unescape segments. The two `true` results confirm that sharing and the cycle were restored.
Related lessons
- JavaScript · Lesson 17 · Advanced · Version: 4
Sources
- ECMAScript 2024 Language Specification — JSON.stringify
- ECMAScript 2024 Language Specification — JSON.parse
- ECMAScript 2024 Language Specification — WeakMap Objects
- ECMAScript 2024 Language Specification — Object.fromEntries
- HTML Standard — StructuredDeserialize
- HTML Standard — Structured cloning API
- RFC 6901 — JavaScript Object Notation (JSON) Pointer