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 '../src/ObjectUnpacker';
import { ProcedureInstruction } from '../src/instructions';
const mapper = createObjectUnpacker();
const data = {
"x": [
{
"a": [
"testa",
"testb"
],
"au": "%system.metadata.author"
}
]
};
const mapperData: ProcedureInstruction = [
{
comment: 'Create the top level result object',
action: 'toObject',
source: '/compact',
target: '/expanded',
keys: ['x'],
values: {
formatted: '%x'
}
},
{
comment: 'process the `formatted` array',
action: 'foreach',
source: '/expanded.formatted',
target: '/expanded.formatted',
loopVar: 'i',
instruction: [
{
comment: 'process the array entry',
action: 'toObject',
source: 'i',
target: 'tmp',
keys: ['a', 'au'],
values: {
another:{
first:'%a.0',
second:'%a.1',
fourth:'%/subs.system.metadata.name'
},
author:'%au'
}
}
]
}
];
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"
}
]
};
ProcedureInstruction = [
{
comment: 'Create the top level result object',
action: 'toObject',
source: '/compact',
target: '/expanded',
keys: ['x'],
values: {
formatted: '%x'
}
},
{
comment: 'process the `formatted` array',
action: 'foreach',
source: '/expanded.formatted',
target: '/expanded.formatted',
loopVar: 'i',
instruction: [
{
comment: 'process the array entry',
action: 'toObject',
source: 'i',
target: 'tmp',
keys: ['a', 'au'],
values: {
another:{
first:'%a.0',
second:'%a.1',
fourth:'%/subs.system.metadata.name'
},
author:'%au'
}
}
]
}
];
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:
{{
"formatted": [
{
"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