Issue
I'm just trying to do the most trivial thing in the world, and am running into an issue parsing inconsistently cased data from various legacy devices.
I'm trying to parse the following JSON in TypeScript
{
"property": 5
}
vs.
{
"Property": 5
}
The best answer I've been able to think of is literally just loop through the keys of the object and run "toUpper" on them, but is there a decent NPM package out there (like json-typescript-mapper but NOT case sensitive) which lets me deserialize an object without having to loop through object keys and manually extract values or write a ton of boilerplate code
I want to parse the JSON to a single unified object schema, say { property }, so I can access it without lots of conditions checking for variations of the name
Solution
One option is to write your custom reviver
function, as the second parameter to JSON.parse
, that transforms plain objects' keys to lower case:
const json = `{"Property": 5,"inner":{"Foo":"foo"}}`;
const obj = JSON.parse(
json,
(_, val) => {
if (Array.isArray(val) || typeof val !== 'object') {
return val;
}
return Object.entries(val).reduce((a, [key, val]) => {
a[key.toLowerCase()] = val;
return a;
}, {});
}
);
console.log(obj);
Answered By - CertainPerformance
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.