1.1.3 • Published 1 year ago

@andrewperson/parse-json-stream v1.1.3

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

Parse-JSON-Stream

This library allows you to parse JSON from an incoming stream and add listeners for when certain objects are found.

Usage

There is a single function, parseJSONStream. This returns an object, the parser, which is then further used.

The parser has 3 functions: 1. onStructure: This takes a string[], the path to the object/array(s) that will cause the callback to fire. It takes the callback as its 2nd argument. 2. write: This takes a Uint8Array representing the next sequential bytes of the json and writes it to the parser, which parses it and fires off the necessary callbacks. 3. finish: This closes the parser and finalises any parsing and callbacks remaining.

Example

import { parseJSONStream } from "@andrewperson/parse-json-stream.js";

const json = `{
    "token": {
        "access_token": "",
        "refresh_token": "",
        "expires_in": 0,
        "termination": 0
    },
    "data": {
        "dailytimetable": {
            "date": "0000-00-00"
        },
        "timetable": {
            "subjects": [
                {
                    "title": "ABC",
                    "teacher": "DEF"
                }
            ]
        }
    }
}`;

let parser = parseJSONStream()
    .onStructure(["token"], (token, _) => console.log(`token: ${token}`))
    .onStructure(["data", "*"], (data, path) => console.log(`${path.join(".")}: ${data}`));

let textEncoder = new TextEncoder();

//Split JSON into parts and pass JSON in sequentially, as if from a stream.
for (let i = 20; i < json.length; i += 20) {
    parser.write(textEncoder.encode(json.substring(i - 20, Math.min(i, json.length))));
}

parser.finish(); // We should be using `await` here, but this isn't an async function. 🤷

/* Output:
token: {
        "access_token": "",
        "refresh_token": "",
        "expires_in": 0,
        "termination": 0
    }
data.dailytimetable: {
            "date": "0000-00-00"
        }
data.timetable: {
            "subjects": [
                {
                    "title": "ABC",
                    "teacher": "DEF"
                }
            ]
        }
*/
1.1.1

1 year ago

1.1.0

1 year ago

1.0.0

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

0.0.7

1 year ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago