Issue
Here is my current object:
{"or_11[and_3][gt@last_closed_sr]":"2019-06-18"}
I would like it to look like:
{
"or_11": {
"and_3": {
"gt@last_closed_sr": "2019-06-18",
}
}
}
What is the best way to do this?
Solution
In general the answer to poorly formatted data is to fix the formatter, not to implement a parser. However, I've worked with systems that encode data like that, so here's a parser.
function parseSquareSeparatedData(data) {
const result = {};
Object.keys(data).forEach((key) => {
const keyParts = key.replace(/]/g, "").split("[");
const last = keyParts.pop();
let resultPointer = result;
keyParts.forEach((keyPart) => {
if (!(keyPart in resultPointer)) {
resultPointer[keyPart] = {};
}
resultPointer = resultPointer[keyPart];
})
resultPointer[last] = input[key];
})
return result;
}
Answered By - Charlie Bamford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.