jsonStringWithUndefined
The jsonStringWithUndefined function serializes an object to JSON, keeping any undefined values within it, which plain JSON would otherwise drop or turn into null.
jsonStringWithUndefined(obj: unknown): Json| Type | Description | |
|---|---|---|
obj | unknown | The object to serialize. |
| returns | Json | The JSON serialization of the object. |
A MergeableStore records that a Cell or Value has been deleted by giving it an undefined value in its MergeableContent and MergeableChanges. Plain JSON.stringify turns those into null, which is a valid Cell or Value, and so the deleted Cell or Value comes back when the JSON is parsed and set or merged. Use this function, and the jsonParseWithUndefined function, instead. The content of a regular Store never contains undefined values, so plain JSON is fine for that.
Each undefined value is written as a string holding just the Unicode object replacement character (U+FFFC), which is how TinyBase's own Persisters and Synchronizers serialize them too. It follows that a string Cell or Value holding just that character is read back as undefined, and so as deleted.
Examples
This example serializes an object that has an undefined value, both with this function and with plain JSON.
import {jsonStringWithUndefined} from 'tinybase';
console.log(jsonStringWithUndefined({species: 'dog', color: undefined}));
// -> '{"species":"dog","color":"\uFFFC"}'
console.log(JSON.stringify({species: 'dog', color: undefined}));
// -> '{"species":"dog"}'
This example serializes the content of a MergeableStore that has had a Row deleted, and then uses it to set the content of another. Plain JSON, by contrast, brings the deleted Row back with a null Cell.
import {
createMergeableStore,
jsonParseWithUndefined,
jsonStringWithUndefined,
} from 'tinybase';
const store = createMergeableStore();
store.setRow('pets', 'fido', {species: 'dog'}).delRow('pets', 'fido');
const content = store.getMergeableContent();
const json = jsonStringWithUndefined(content);
const restoredStore = createMergeableStore();
restoredStore.setMergeableContent(jsonParseWithUndefined(json));
console.log(restoredStore.getTables());
// -> {}
const plainJson = JSON.stringify(content);
const wronglyRestoredStore = createMergeableStore();
wronglyRestoredStore.setMergeableContent(JSON.parse(plainJson));
console.log(wronglyRestoredStore.getTables());
// -> {pets: {fido: {species: null}}}
Since
v10.2.0