Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@quadient/evolve-data-transformations
Advanced tools
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
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.
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>
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.
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"}}
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"}
]}
Async streaming CSV parser.
CsvParser
can be used to process csv content as strings. It produces
event objects and sends them to a callback.
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' ]
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).FAQs
Library for data transformations.
We found that @quadient/evolve-data-transformations demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.