jsonTrim
Bard AI
by Abhishek Kumar
JavaScript
const trimJson = (text) => {
const types = ["object", "array", "string", "number", "boolean", "null"];
for (const type of types) {
if (type === "object") {
const startIndex = text.indexOf("{");
const endIndex = text.lastIndexOf("}");
if (startIndex !== -1 && endIndex !== -1) {
return text.slice(startIndex, endIndex + 1);
}
} else if (type === "array") {
const startIndex = text.indexOf("[");
const endIndex = text.lastIndexOf("]");
if (startIndex !== -1 && endIndex !== -1) {
const objects = text.slice(startIndex + 1, endIndex).split("},{");
return `[${objects.map(object => object.trim())}]`;
}
} else {
const regex = new RegExp(`^[${type}]+`, "g");
const match = regex.exec(text);
if (match !== null) {
return match[0].replace(/\u00A0/g, "") + "]";
}
}
}
return "";
};
// A valid JSON string
const text1 = '{"foo":"bar"}';
console.log(trimJson(text1)); //=> '{"foo":"bar"}'
// A JSON string with extra characters at the end
const text2 = '{"foo":"bar"} xyz';
console.log(trimJson(text2)); //=> '{"foo":"bar"}'
// A JSON string with extra characters at the beginning and the end
const text3 = 'abc {"foo":"bar"} xyz';
console.log(trimJson(text3)); //=> '{"foo":"bar"}'
// A JSON string with non-ASCII characters at the beginning and the end
const text4 = '\uFEFF{"foo":"bar"}\u0000';
console.log(trimJson(text4)); //=> '{"foo":"bar"}'
// An invalid JSON string
const text5 = '{"foo":';
console.log(trimJson(text5)); //=> ''
const text6 = 'asdbaj asfkjs [{"name":"animations","locked":true},{"name":"cdk","locked":false}] 2304923 sadfj';
console.log(trimJson(text6));
const text7 = ' [{"name":"animations","locked":true},{"name":"cdk","locked":false}] 2304923 sadfj';
console.log(trimJson(text7));