CC-1523: YAML-JSON conversion

This commit is contained in:
David Marshall 2023-04-19 18:59:37 -04:00
parent 1bc88728f0
commit c8e306d4f4
7 changed files with 202 additions and 6 deletions

View file

@ -65,6 +65,8 @@
"Parse TLV",
"CSV to JSON",
"JSON to CSV",
"YAML to JSON",
"JSON to YAML",
"Avro to JSON",
"CBOR Encode",
"CBOR Decode"

View file

@ -0,0 +1,48 @@
/**
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2018
* @license Apache-2.0
*/
import YAML from 'yaml'
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
/**
* JSON to YAML operation
*/
class JSONToYAML extends Operation {
/**
* JSONToYAML constructor
*/
constructor() {
super();
this.name = "JSON to YAML";
this.module = "Default";
this.description = "Converts JSON data to a YAML.";
this.infoURL = "https://yaml.org/spec/1.2.2/";
this.inputType = "string";
this.outputType = "string";
this.args = [];
}
/**
* @param {JSON} input
* @param {Object[]} args
* @returns {string}
*/
run(input, args) {
const doc = new YAML.Document();
try {
doc.contents = JSON.parse(input.replace(/(\w+):/gm, `"$1":`));
return doc.toString()
} catch (err) {
throw new OperationError("Unable to parse JSON to YAML: " + err.toString());
}
}
}
export default JSONToYAML;

View file

@ -0,0 +1,53 @@
/**
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2018
* @license Apache-2.0
*/
import YAML from 'yaml'
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
/**
* YAML To JSON operation
*/
class YAMLToJSON extends Operation {
/**
* YAMLToJSON constructor
*/
constructor() {
super();
this.name = "YAML to JSON";
this.module = "Default";
this.description = "Converts YAML data to a JSON based on the definition in RFC 4180.";
this.infoURL = "https://en.wikipedia.org/wiki/JSON";
this.inputType = "string";
this.outputType = "JSON";
this.args = [
{
name: "Use Spaces",
type: "number",
value: 0
}
];
}
/**
* @param {YAML} input
* @param {Object[]} args
* @returns {string}
*/
run(input, args) {
const [spaces] = args;
try {
return JSON.stringify(YAML.parseDocument(input).toJSON(), null, spaces);
} catch (err) {
throw new OperationError("Unable to parse YAML To JSON: " + err.toString());
}
}
}
export default YAMLToJSON;