-2

Transform this result in json valid.

"{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}"
  • 4
    Does this answer your question? [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Aziz.G Dec 06 '19 at 19:21

1 Answers1

1

Just parse it via JSON.parse() to convert the string into a JSON object.

let jsonString = "{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}";
console.log(JSON.parse(jsonString));

let brokenJsonString = '{ "key": "<div class="coolCSS">some text</div>" }';
try {
  console.log(JSON.parse(brokenJsonString));
} catch (e) {
  console.log("Exception thrown when parsing.", e.toString());
}

Be careful when parsing strings because (as @Fallenreaper noted) malformed or invalid JSON is going to result in an error thrown. So wrap your JSON.parse() with try...catch statement (more about it here).

Broken/malformed can be handled with libraries like this but use them when you absolutely need it and always read the docs.

Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
  • 1
    If you are going to suggest using JSON.parse, you should explain to the user to wrap it in a try/catch because if it is malformed JS it will kill the console. You need to account for malformed jsonstrings. Just letting parse do its thing, and then catching an error is the easiest most straight forward approach. – Fallenreaper Dec 06 '19 at 19:31
  • Thanks for the note! – Goran Stoyanov Dec 06 '19 at 19:54