Skip to content

DreamPast/efjson

Repository files navigation

A Streaming and Event-driven JSON Parser

English 简体中文

Features

  • no runtime dependencies
  • supports JSON5 and JSONC
  • stream parser requires minimal memory when no events are triggered

Installation

Installation via npm

npm install efjson

Example

Stream Parsing

import { jsonStreamParse } from "efjson";

const json = `{
"null":null,"true":true,"false":false,
"string":"string,\\"escape\\",\\uD83D\\uDE00,😊",
"integer":12,"negative":-12,"fraction":12.34,"exponent":1.234e2,
"array":["1st element",{"object":"nesting"}],
"object":{"1st":[],"2st":{}}
}`;
for (const token of jsonStreamParse(json)) console.log(token);

Event Response

import { jsonEventParse } from "efjson";

const json = `
{
  "null": null,
  "true": true,
  "false": false,

  "string": "string",
  "string_with_escape": "string with \\"escape\\"",
  "string_with_unicode_escape": "string with \\uD83D\\uDE00",
  "string_with_unicode": "string with 😊",

  "integer": 1234,
  "negative": -1234,
  "number": 1234.5678,
  "number_with_exponent": 1.234e2,

  "array": [
    "this is the first element",
    {
      "object": "a nesting object"
    }
  ],
  "object": {
    "1st": [],
    "2st": {}
  }
}
`;

jsonEventParse(json, {
  object: {
    set(key, value) {
      console.log(key, value);
    },
  },
});

Normal Parsing

import { jsonNormalParse } from "efjson";

const json = `
{
  "null": null,
  "true": true,
  "false": false,

  "string": "string",
  "string_with_escape": "string with \\"escape\\"",
  "string_with_unicode_escape": "string with \\uD83D\\uDE00",
  "string_with_unicode": "string with 😊",

  "integer": 1234,
  "negative": -1234,
  "number": 1234.5678,
  "number_with_exponent": 1.234e2,

  "array": [
    "this is the first element",
    {
      "object": "a nesting object"
    }
  ],
  "object": {
    "1st": [],
    "2st": {}
  }
}
`;

console.log(jsonNormalParse(json));

References

JSON Specification: RFC 4627 on JSON

JSON State Diagram: JSON

JSON5 Specification: The JSON5 Data Interchange Format

JSON Pointer: JavaScript Object Notation (JSON) Pointer

Relative JSON Pointers: Relative JSON Pointers