Given the following log object:
{
"message": "login: error {\"error\":{\"message\":\"Network Error\",\"name\":\"Error\",\"stack\":\"Error: Network Error\\n at something (somewhere)\\n at something (somewhere)\",\"config\":{\"url\":\"/a/place\",\"method\":\"get\",\"headers\":{\"Accept\":\"application/json, text/plain, */*\",\"Authorization\":\"bla blablabla\",\"X-Amzn-Trace-Id\":\"yadiyadiyadi\"},\"baseURL\":\"verygoodplace"}}}",
"level": "warning",
"sessionId": "blablabla"
}
How can I remove the message.headers.Authorization entry completely?
Since it appears inside a string, I can't (directly) use lodash unset, and I somehow need to alter the string.
I would recommend to clean message a bit so it can be parsed with JSON.parse(). It looks like discarding text before the first { will be all that's needed.
Parsing will create a JS object that is easy to manipulate, after which you can use JSON.stringify() to convert it back to a similar string as what you started with.
It may seem like a lot of steps, but doing this kind of string manipulation directly could be an even bigger pain in the you-know-where.
Working demo:
const logObj = {
"message": "login: error {\"error\":{\"message\":\"Network Error\",\"name\":\"Error\",\"stack\":\"Error: Network Error\\n at something (somewhere)\\n at something (somewhere)\",\"config\":{\"url\":\"/a/place\",\"method\":\"get\",\"headers\":{\"Accept\":\"application/json, text/plain, */*\",\"Authorization\":\"bla blablabla\",\"X-Amzn-Trace-Id\":\"yadiyadiyadi\"},\"baseURL\":\"verygoodplace\"}}}",
"level": "warning",
"sessionId": "blablabla"
}
const index = logObj.message.indexOf("{");
const jsonText = logObj.message.substring(index);
const parsed = JSON.parse(jsonText);
delete parsed.error.config.headers.Authorization; // remove unwanted node
console.log("The cleaned message:");
console.log(JSON.stringify(parsed, undefined, 2)); // print with indentation
const prefix = logObj.message.substring(0, index);
logObj.message = prefix + JSON.stringify(parsed);
console.log("The updated logObj:");
console.log(JSON.stringify(logObj, undefined, 2)); // print with indentation
Note - to make this work I had to change verygoodplace" to verygoodplace\", it looks like you made an error when preparing the log object for use in the question.