H Varma
H Varma

Reputation: 640

Convert the num or boolean type json object from string type to its original

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

Answers (2)

Nina Scholz
Nina Scholz

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

Stan
Stan

Reputation: 26511

  1. You need to make sure your actual server returns the correct types since JSON understands boolean and integer.

  2. 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

Related Questions