TypeScript Object Unpacker
This program takes a JSON object and convertes it to a new JSON object using a mapping specification, also written as JSON.
There are some examples of how to use the mapper in the test
directory, and a simple TypeScript
example follows:
import { createObjectUnpacker } from './ObjectUnpacker';
const mapper = createObjectUnpacker();
const data = {
"x": [
{
"a": [
"testa",
"testb"
],
"au": "%system.metadata.author"
}
]
};
const mapperData = {
"x": {
"rewriteKey": "expanded"
},
"a": {
"rewriteKey": "another",
"assignKeys": [
"s",
"t",
"u"
],
"rewriteValue": {
"first": "%s",
"second": "%t",
"third": "%u",
"fourth": "%/subs.system.metadata.name"
}
},
"au": {
"rewriteKey": "author"
}
};
const refs = {
system: {
metadata: {
name: 'The System Name',
author: 'A. Programmer',
},
},
};
const expanded: object = mapper.convert(refs, data, mapperData);
console.log(JSON.stringify(expanded, null, 2));
The same example in JavaScript
const unpacker = require("object-unpacker")
const data = {
"x": [
{
"a": [
"testa",
"testb"
],
"au": "%system.metadata.author"
}
]
};
const mapperData = {
"x": {
"rewriteKey": "expanded"
},
"a": {
"rewriteKey": "another",
"assignKeys": [
"s",
"t",
"u"
],
"rewriteValue": {
"first": "%s",
"second": "%t",
"third": "%u",
"fourth": "%/subs.system.metadata.name"
}
},
"au": {
"rewriteKey": "author"
}
};
const refs = {
system: {
metadata: {
name: 'The System Name',
author: 'A. Programmer',
},
},
};
const expanded = unpacker.mapper.convert(refs, data, mapperData);
console.log(JSON.stringify(expanded, null, 2));
Running the example code
- Run
npm install
- Create
scratch.ts
in the src
directory. - Compile it using the
tsc
command - Run it using
node dist/scratch.js
- Or combine the previous two steps as
tsc && node dist/scratch.js
The output should look like this:
{
"expanded": [
{
"another": {
"first": "testa",
"second": "testb",
"fourth": "The System Name"
},
"author": "A. Programmer"
}
]
}
Running the example code in a web browser
- Run
npm install
- Run
npm install -g webpack
- Run
npm install -g webpack-cli
- Run the
webpack
command in the project root directory. - Open the
test/index.html
file using a web browser (Only tested using Brave browser) - Paste your JSON into the first two text areas and click
Execute