JSON transform
Just a tool for myself
by Amy L
HTML
<p>
<label for="in">Input:</label>
<br/>
<textarea id="in" cols="80" rows="10">{ "hello": "world", "foo": "bar" }
</textarea>
</p>
<fieldset>
<legend>Dimensions</legend>
<label for="dimType">Type:</label>
<input type="text" id="dimType" placeholder="type" value="text" />
<label for="dimTarget">Target:</label>
<input type="text" id="dimTarget" placeholder="target" value="" />
</fieldset>
<p>
<button id="convert">Convert</button>
<button id="copy">Copy output to clipbard</button>
<input type="checkbox" id="includeArray" checked="checked"/> <label for="includeArray">Copy includes []</label>
</p>
<p>
<label for="out">Output:</label>
<br/>
<textarea id="out" cols="80" rows="15" readonly="readonly"></textarea>
</p>
TypeScript
init();
function init(): void {
let convertEl: HTMLElement = document.querySelector('button#convert');
let copyEl: HTMLElement = document.querySelector('button#copy');
convertEl.addEventListener('click', onClickConvert);
copyEl.addEventListener('click', onClickCopy);
}
function getInput(): ConfigInterface {
let inputEl: HTMLElement = document.querySelector('textarea#in');
let contentStr: string = inputEl.value;
let contentJson: ConfigInterface;
try {
contentJson = JSON.parse(contentStr);
} catch (e) {
console.error(e);
alert(e);
}
return contentJson;
}
function writeOutput(configuration: Property[]): void {
let outputEl: HTMLElement = document.querySelector('textarea#out');
let outputStr: string = JSON.stringify(configuration);
outputEl.value = outputStr;
}
function convert(config: ConfigInterface): Property[] {
let dimType: string = document.querySelector('input#dimType').value || 'text';
let dimTarget: string = document.querySelector('input#dimTarget').value;
let properties: Property[] = [];
for (let key in config) {
if (config.hasOwnProperty(key) {
let property: Property = {
key: key,
value: config[key],
dimensions: {
type: dimType
}
};
if (dimTarget) {
property.dimensions.target = dimTarget;
}
properties.push(property);
}
}
return properties;
}
function onClickConvert(e: Event): void {
let json: ConfigInterface = getInput();
let properties: Property[] = convert(json);
writeOutput(properties);
}
function onClickCopy(e: Event): void {
let outputEl: HTMLElement = document.querySelector('textarea#out');
let includeArrayEl: HTMLElement = document.querySelector('input#includeArray');
outputEl.focus();
if (includeArrayEl.checked) {
outputEl.select();
} else {
outputEl.setSelectionRange(1, outputEl.value.length-1);
}
try {
let successful: boolean = document.execCommand('copy');
let msg: string = (successful)...