I get some JSON from a moleculer.js return call that looks like this:
{ "output": "{ \"success\" : { \"msg\" : \"user found\"}}" }
{ "output": "{ \"error\" : { \"msg\" : \"user not found\"}}" }
...which is horrible to try and parse and drill down to access the various key:value pairs. If possible, I'd like to be able to 'sanitize' the JSON so that it comes out like this:
{ output: { error : { msg : "user not found"} } }
leaving only the last value in quotes, since it contains human-readable text with spaces. Then I could just use simple object notation to access it. Something like console.log(output.error.msg)
to get the value/contents of the msg key.
I was thinking something along the lines of JSON.stringify-ing the object then striping out the quotes I don't want, but it seems rather hacky and would contain hardcoded parameters. I'm hoping for some inspiration and/or tips in the right direction. Something elegant and re-usable would be nice... a loop comes to mind, but not sure how to 'jump out' once I've changed what I want.
Alternatively, any tricks on just accessing that JSON directly without striping characters or conversion would be a good thing too. Much appreciation in advance.
Turns out the easiest solution found so far (at the time of this writing) is to just re-parse the value string back into JSON and concatenate it into a new JSON.
Example code:
// call is the original returned data from a microservice:
// { "output": "{ \"success\" : { \"msg\" : \"user found\" } }" }
let returned_output = JSON.parse(call.output)
// gives us: { "success" : { "msg" : "user found" } }
return { "output": returned_output }
// gives us: { "output": { "success" : { "msg" : "user found" } } )