So I'm trying to convert a markdown file and send it over a rest API, and render it in the frontend. The problem is that the newlines, and other things get lost while trying to convert it back.
How do I render it back in a way that the original markdown is preserved?
Is there a standard way of doing this?
Tried to convert markdown by json.stringify, sent it over the api, tried to convert it back to markdown but doesn't work like original anymore.
You can either send the original file as a string, or if that is not an option, you can format the object with this function:
const object = {a:[15,3457,15,"afbsv",[4,34,36],{
l: "dsfvszd",
qwe: 238475463,
iuggbsf: ["AEfs",],
afafwwa:{afafwafaw:{r:"4"}}
}]}
document.write(`<pre>${format(object)}</pre>`);
function format(object) {
let result = "";
processObject(object, 2);
function processObject(object, depth, isObjectValue = false, trailingComma = "") {
if (Array.isArray(object)) {
result += `${isObjectValue ? " " : "<br>" + " ".repeat(depth - 2)}[`;
for (let i = 0; i < object.length; i++) {
const element = object[i],
trailingComma = i + 1 === object.length ? "" : ",";
switch (typeof element) {
case "object":
processObject(element, depth + 2, false, trailingComma);
break;
case "string":
result += `<br>${" ".repeat(depth)}"${element}"${trailingComma}`;
break;
case "number":
result += `<br>${" ".repeat(depth) + element}${trailingComma}`;
break;
}
}
result += `<br>${" ".repeat(depth - 2)}]${trailingComma}`;
} else {
result += `${isObjectValue ? " " : "<br>" + " ".repeat(depth - 2)}{`;
let keyIndex = 0,
keyCount = Object.keys(object).length;
for (key in object) {
const value = object[key],
trailingComma = ++keyIndex === keyCount ? "" : ",";
switch (typeof value) {
case "object":
result += `<br>${" ".repeat(depth)}"${key}":`;
processObject(value, depth + 2, true, trailingComma);
break;
case "string":
result += `<br>${" ".repeat(depth)}"${key}": "${value}"${trailingComma}`;
break;
case "number":
result += `<br>${" ".repeat(depth)}"${key}": ${value}${trailingComma}`;
break;
}
}
result += `<br>${" ".repeat(depth - 2)}}${trailingComma}`;
}
}
return result;
}
Just use format(objectGoesHere)
and it will return a string that is formatted for HTML.