npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@quadient/evolve-data-transformations

v0.0.10

Published

Library for data transformations.

Downloads

328

Readme

Data Transformations Package

Overview

The Data Transformations package contains helper utilities to wrestle with JSON, XML and CSV data formats.

Add to project:

npm install @quadient/evolve-data-transformations

Table of Contents

XML

Async streaming XML Parser and Writer.

XmlParser can be used to process strings with parts of the XML content. The callback given to parser constructor receives events of type XmlEvent.

XmlWriter is the opposite component. It receives XmlEvent objects through the write method and the callback given to constructor receives a string with the XML content.

To integrate XML processing with streams there are TransformStream classes StringToXmlTransformStream and XmlToStringTransformStream for convenient use with streams.

XML Example

const writer = new XmlWriter(async (str) => {
    console.log(str);
});

const parser = new XmlParser(async (event) => {
    if (event.type === XmlEventType.START_TAG) {
        let elem = event.details as ElementDetails;
        if (elem.name == "name") {
            elem.name = "fixedName"
        }
    } else if (event.type === XmlEventType.END_TAG) {
        if (event.details === "name") {
            event.details = "fixedName"
        }
    }
    await writer.write(event);
});

await parser.parse(`<person><name>Fred</name></person>`);
await parser.flush(); // must be called at the end of parsing
await writer.flush(); // must be called at the end of writing

Output:

<person><fixedName>Fred</fixedName></person>

JSON

Async streaming JSON Parser and Writer.

JsonParser can be used to process strings with parts of the JSON content. The callback given to parser constructor receives events of type JsonEvent.

JsonWriter is the opposite component. It receives JsonEvent objects in the write method and the callback given to constructor receives a string with the JSON content.

To integrate XML processing with streams there are TransformStream classes StringToJsonTransformStream and JsonToStringTransformStream for convenient use with streams.

JSON Example

let writer = new JsonWriter(async (str) => {
    console.log(str);
});

let parser = new JsonParser(async (event) => {
    if(event.type === JsonEventType.PROPERTY_NAME && event.data === "name") {
        event.data = "fixedName";
    }
    await writer.write(event);
})

await parser.parse(`{"person": {"name":"Fred"}}`);
await parser.flush(); // must be called at the end of parsing
await writer.flush(); // must be caleld at the end of writing

Output:

{"person":{"fixedName":"Fred"}}

Partial materialization

Processing JSON using events is efficient with respect to used memory during the transformation, but is quiet intricate. Especially when compared to fully deserializing json to object using JSON.parse. In most of the situations it will be possible to use a combination of both approaches. When dealing with large data it often appears, that data structure contains some array with many members. In such case it would be useful to handle all JSON input with streaming approach, but the members of array could be safely deserialized to objects as the individual members of the array are small enough to fit in memory.

For this approach there is a set of helper classes used for partial materialization of the json data. One can specify which parts of the json structure will be materialized (deserialized to object) with a json path. A special event JsonEvent.ANY_VALUE will be triggered for those deserialized parts.

Here is an example using JsonMaterializingParser class:

const inputJson = '{"people": [{"firtsName": "Mike", "lastName": "Smith"}, {"firstName": "Foo", "lastName": "Bar"}]}';
const materializedPaths = [".people[*]"];
const writer = new JsonWriter(async (s) => {
    console.log(s);
});
const parserCallback = async function (event: JsonEvent) {
    if (event.type === JsonEventType.ANY_VALUE) {
        const o = event.data;
        o.full_name = o.firstName + " " + o.lastName;
    }
    await writer.write(event);
}
const parser = new JsonMaterializingParser(parserCallback, { materializedPaths });
await parser.parse(inputJson);
await parser.flush();
await writer.flush();

Output:

{"people":[
  {"firstName":"Mike","lastName":"Smith","full_name":"Mike Smith"},
  {"firstName":"Foo","lastName":"Bar","full_name":"Foo Bar"}
]}

And here follows example with streams, making use of JsonMaterializingTransformStream:

const input = new StringReadableStream(
    '{"people": [{"firstName": "Mike", "lastName": "Smith"}, {"firstName": "Foo", "lastName": "Bar"}]}'
);
const materializedPaths = [".people[*]"];
const transformer = new TransformStream<JsonEvent, JsonEvent>({
    transform(event, controller) {
        if (event.type === JsonEventType.ANY_VALUE) {
            const o = event.data;
            o.full_name = o.firstName + " " + o.lastName;
        }
        controller.enqueue(event);
    }
});
await input
    .pipeThrough(new StringToJsonTransformStream())
    .pipeThrough(new JsonMaterializingTransformStream({materializedPaths}))
    .pipeThrough(transformer)
    .pipeThrough(new JsonToStringTransformStream())
    .pipeTo(new ConsoleLogWritableStream());

Output:

{"people":[
  {"firstName":"Mike","lastName":"Smith","full_name":"Mike Smith"},
  {"firstName":"Foo","lastName":"Bar","full_name":"Foo Bar"}
]}

CSV

Async streaming CSV parser.

CsvParser can be used to process csv content as strings. It produces event objects and sends them to a callback.

CSV Example

const p = new CsvParser(async (event) => {
    console.log(event.type + " - " + event.data);
});
await p.parse('head')
await p.parse('er1,header2\nvalue1,value2');
await p.flush();

Output:

header - [ 'header1', 'header2' ]
values - [ 'value1', 'value2' ]

Streams

The following example illustrates how the stream-compatible helper classes can be used in case the input is in the form of ReadableStream.

import {StringToXmlTransformStream, XmlEventType} from "@quadient/evolve-data-transformations";

(async function () {
    const response = await fetch("https://httpbin.org/xml");
    const stream = response.body;
    stream
        .pipeThrough(new TextDecoderStream())
        .pipeThrough(new StringToXmlTransformStream())
        .pipeTo(new ConsoleLogWritableStream());
})()

class ConsoleLogWritableStream extends WritableStream {
    constructor() {
        super({
            write(chunk) {
                console.log(chunk);
            }
        })
    }
}

Following stream-compatible classes are available:

  • StringToXmlTransformStream - transforms stream of strings to stream of XmlEvent objects (xml deserialization).
  • XmlToStringTransformStream - transforms stream of XmlEvent objects to a string stream (xml serialization).
  • StringToJsonTransformStream - transforms stream of strings to stream of JsonEvent objects (json deserialization).
  • JsonToStringTransformStream - transforms stream of JsonEvent objects to a string stream (json serialization).
  • JsonMaterializingTransformStream - transforms stream of JsonEvent objects to JsonEvent objects. Some events just pass through, some are consumed and translated to special event containing an object representing the materialized part of the JSON part.
  • StringToCsvTransformStream - transforms stream of strings to CsvEvent objects (csv deserialization).