v1.2.2

Serialization

Last updated


This page explains how the node tree is written back out as JSON: the node-level json getter, the root-level editor.json and editor.export(), and how the two root paths differ.

Node Level: JSONEditorNode.json


JSONEditorNode.json (a getter) recursively calls the private #json() (JSONEditorNode.js:157), returning a JavaScript value per node type:
Node TypeReturns
arrayAn array of each child's #json() result
objectAn object keyed by each child's key
booleanvalue.toLowerCase() === "true"
numberNumber(value)
anything elseThe raw value

When an object node builds its object, keyless children are skipped — except when that object node itself sits inside an array (this.parent.type === "array"), in which case a keyless child gets the current count of collected keys as a numeric key (JSONEditorNode.js:173). For duplicate keys, the later one wins.

Root Level: editor.json vs. editor.export()


The two root-level paths filter differently:
PathFilter Condition (JSONEditor.js)Output
editor.json (getter, lines 267-277)Only children where e.key is truthyA 4-space-indented JSON string
editor.export() (lines 289-310)Children where e.key is truthy, or any child when children.length === 1Downloads NanoJSON-{timestamp}.json, also 4-space-indented

Both paths build an object as the root; a keyless child is written under the key 0 (result[e.key || 0]).

Importing an Array


The root's editor.type is always "object". When the imported data is an array, the root-level children are keyless, so the two paths diverge:
Imported Dataeditor.jsoneditor.export() Download
[1]"{}"{"0": 1}
[1, 2]"{}"{}
{"a": 1}{"a": 1}{"a": 1}

A root-level array is never written out as an array. To keep an array root, wrap it in an object before passing it in (for example { "items": [...] }).

Example


editor.json is printed after the initial render and after every edit:
  1. <section id="editor"></section>
  2. <script>
  3. const editor = new JSONEditor({
  4. id: "editor",
  5. fill: false,
  6. collapsed: false,
  7. json: { count: 1, list: [1, "two", true], nested: { ok: false } },
  8. when: {
  9. rendered: () => console.log(editor.json),
  10. updated: () => console.log(editor.json),
  11. },
  12. });
  13. </script>
Live preview · @pardnchiu/nanojson@1.2.2

Importing a root-level array: the root children are keyless, so editor.json is {}:
  1. <section id="editor"></section>
  2. <script>
  3. const editor = new JSONEditor({
  4. id: "editor",
  5. fill: false,
  6. json: [1, 2],
  7. when: {
  8. rendered: () => console.log("editor.json:", editor.json),
  9. },
  10. });
  11. </script>
Live preview · @pardnchiu/nanojson@1.2.2

Further Reading


中文