2018-05-27 23:07:09 +02:00
|
|
|
/**
|
|
|
|
* @author n1474335 [n1474335@gmail.com]
|
2018-11-21 05:32:59 +01:00
|
|
|
* @author Phillip Nordwall [phillip.nordwall@gmail.com]
|
2018-05-27 23:07:09 +02:00
|
|
|
* @copyright Crown Copyright 2016
|
|
|
|
* @license Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
import vkbeautify from "vkbeautify";
|
|
|
|
import Operation from "../Operation";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* JSON Beautify operation
|
|
|
|
*/
|
|
|
|
class JSONBeautify extends Operation {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* JSONBeautify constructor
|
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
|
|
|
|
this.name = "JSON Beautify";
|
|
|
|
this.module = "Code";
|
|
|
|
this.description = "Indents and prettifies JavaScript Object Notation (JSON) code.";
|
|
|
|
this.inputType = "string";
|
|
|
|
this.outputType = "string";
|
|
|
|
this.args = [
|
|
|
|
{
|
|
|
|
"name": "Indent string",
|
|
|
|
"type": "binaryShortString",
|
2018-11-23 17:05:51 +01:00
|
|
|
"value": " "
|
2018-11-21 05:32:59 +01:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"name": "Sort Object Keys",
|
|
|
|
"type": "boolean",
|
|
|
|
"value": false
|
2018-05-27 23:07:09 +02:00
|
|
|
}
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} input
|
|
|
|
* @param {Object[]} args
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
run(input, args) {
|
2018-11-23 17:05:51 +01:00
|
|
|
const [indentStr, sortBool] = args;
|
|
|
|
|
2018-05-27 23:07:09 +02:00
|
|
|
if (!input) return "";
|
2018-11-21 05:32:59 +01:00
|
|
|
if (sortBool) {
|
|
|
|
input = JSON.stringify(JSONBeautify._sort(JSON.parse(input)));
|
|
|
|
}
|
2018-05-27 23:07:09 +02:00
|
|
|
return vkbeautify.json(input, indentStr);
|
|
|
|
}
|
|
|
|
|
2018-11-21 05:32:59 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Sort JSON representation of an object
|
|
|
|
*
|
|
|
|
* @author Phillip Nordwall [phillip.nordwall@gmail.com]
|
|
|
|
* @private
|
|
|
|
* @param {object} o
|
|
|
|
* @returns {object}
|
|
|
|
*/
|
|
|
|
static _sort(o) {
|
|
|
|
if (Array.isArray(o)) {
|
|
|
|
return o.map(JSONBeautify._sort);
|
|
|
|
} else if ("[object Object]" === Object.prototype.toString.call(o)) {
|
|
|
|
return Object.keys(o).sort().reduce(function(a, k) {
|
|
|
|
a[k] = JSONBeautify._sort(o[k]);
|
|
|
|
return a;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
return o;
|
|
|
|
}
|
2018-05-27 23:07:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export default JSONBeautify;
|