Reputation: 640
In my nodejs app,I had a json object where it had combination of string,num and boolean type .But the boolean and num type is also represented as string.
Eg: `{"name":"sam","age":"24","isMarried":"false"}`
Here age and isMarried are num and boolean type but represented as string type.So is there any way,that above json key value type is identified and it gets converted in to respective variable type.i.e to
{"name":"sam","age":24,"isMarried":false}
.`
Any help appreciated.Thanks!
Upvotes: 0
Views: 948
Reputation: 386654
I suggest to use a mapper for the keys with the wanted callback for converting the items.
var data = { "accounting": [{ "firstName": "John", "lastName": "Doe", "age": "23", married: "true" }], "sales": [{ "firstName": "Sally", "lastName": "Green", "age": "27", married: "false" }] },
map = [
{ key: 'age', cb: Number },
{ key: 'married', cb: function (v) { return v === 'true'; } }
];
Object.keys(data).forEach(function (k) {
data[k].forEach(function (a) {
map.forEach(function (b) {
if (b.key in a) {
a[b.key] = b.cb(a[b.key]);
}
});
});
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 26511
You need to make sure your actual server returns the correct types since JSON understands boolean and integer.
You need to create js function that will take care of that. This is not that easy in JS because it has no tryParse.
Here is an example: https://jsfiddle.net/cr4qe1an/
var str = '{"name":"sam","age":"24","isMarried":"false"}';
var obj = JSON.parse(str);
Object.keys(obj).forEach((x) => {
if (obj[x] === 'false' || obj[x] === 'true') {
obj[x] = obj[x] === 'true';
}
if (!isNaN(parseInt(obj[x], 10))) {
obj[x] = parseInt(obj[x], 10); // This is bad, '1abc' will be 1
}
});
Upvotes: 1