@quadient/evolve-data-transformations
v0.0.10
Published
Library for data transformations.
Downloads
328
Keywords
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 ofXmlEvent
objects (xml deserialization).XmlToStringTransformStream
- transforms stream ofXmlEvent
objects to a string stream (xml serialization).StringToJsonTransformStream
- transforms stream of strings to stream ofJsonEvent
objects (json deserialization).JsonToStringTransformStream
- transforms stream ofJsonEvent
objects to a string stream (json serialization).JsonMaterializingTransformStream
- transforms stream ofJsonEvent
objects toJsonEvent
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 toCsvEvent
objects (csv deserialization).