1

I have a scenario where many fields in JSON response that are coming as string ("true"/"false").

Now I need to replace all of the values from string to Boolean in one shot via Javascript.

Sample:

{
    field1: "true",
    field2: "false"
}

Expected:

{
    field1: true,
    field2: false
}

This is a sample. My JSON response is very huge with many objects and arrays.

hong4rc
  • 3,999
  • 4
  • 21
  • 40
  • 3
    Please post your attempts. – jhpratt Jul 15 '18 at 05:42
  • 2
    Are you in control of generating your JSON response? If so, just fix your response. JSON supports booleans. Why not use them? Anyway, you can convert `"false"` to `false` and `"true"` to `true` with `JSON.parse`. [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods may help here as well. – Sebastian Simon Jul 15 '18 at 05:45
  • 2
    Possible duplicate of [How can I convert a string to boolean in JavaScript?](https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – Alexander Jul 15 '18 at 05:45
  • @Xufox No, this is aleardy a valid object, not a string. – Chayim Friedman Jul 15 '18 at 06:10
  • @Alexander No, this isn't duplicate. There is converting a single variable - here is converting a whole object. – Chayim Friedman Jul 15 '18 at 06:11
  • 1
    There are no absolute same questions on the site, but the above mentioned topic aswer how to cast object fields to boolean ,@חייםפרידמן – Alexander Jul 15 '18 at 06:21
  • @Alexander While I agree with you that there are no absolute same questions, I do agree that while that link may help, this question is sufficiently different to not warrant a close vote. – Blue Jul 15 '18 at 06:25
  • @חייםפרידמן What I mean is that `JSON.parse("true") === true` and `JSON.parse("false") === false`. – Sebastian Simon Jul 15 '18 at 14:29

4 Answers4

11

The JSON.parse reviver parameter can be used to exclude or modify values:

var j = '{"field1":"true","field2":"false"}';

var o = JSON.parse(j, (k, v) => v === "true" ? true : v === "false" ? false : v);

console.log(o);
Slai
  • 22,144
  • 5
  • 45
  • 53
  • I didn't know about the reviver function. This is pretty cool, and an alternative (And works recursively!). – Blue Jul 15 '18 at 06:35
0

Here's a nice recursive convertBools function:

function convertBools(obj) {
  const newObj = {};
  
  if (typeof obj !== 'object') {
    return obj;
  }
  
  for (const prop in obj) {
    if (!obj.hasOwnProperty(prop)) {
      continue;
    }
    if (Array.isArray(obj[prop])) {
      newObj[prop] = obj[prop].map(val => convertBools(val));
    } else if (obj[prop] === "true") {
      newObj[prop] = true;
    } else if (obj[prop] === "false") {
      newObj[prop] = false;
    } else {
      newObj[prop] = convertBools(obj[prop]);
    }
  }
  
  return newObj;
}

// Some examples below:
const obj1 = {
  field1: "true",
  field2: "false"
};

const obj2 = {
  field1: "true",
  field2: "asdf",
  field3: "false",
  field4: {
    field4a: "true",
    field4b: "asdf",
    field4c: ["a", {"array1": "true"}, "c"],
  }
}

const ret1 = convertBools(obj1);

console.log(ret1);

const ret2 = convertBools(obj2);

console.log(ret2);
Blue
  • 22,608
  • 7
  • 62
  • 92
0

you can try something like this as well.

let obj = {
    field1: "true",
    field2: "false",
    field3: "SomeOtherValueThanBoolean"
};

for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        obj[prop] = (obj[prop] == 'true' || obj[prop] == 'false')? obj[prop] === 'true': obj[prop] ;
    }
}

console.log(obj);
Syed Arif Iqbal
  • 1,830
  • 12
  • 16
  • As stated in his original question "My JSON response is very huge with many objects and arrays.". This answer does not satisfy that. – Blue Jul 15 '18 at 06:27
0

My version, does not modify source object, returns new object with parsed booleans:

const object = {
  "test": "true",
  "test1": false,
  "test2": "false",
  "test3": 5,
}

console.log(parseBooleansInObj(object));


function parseBooleansInObj(object) {
  const newObject = { ...object };
  Object.keys(newObject)
    .forEach((objKey) => {
      let value = newObject[objKey];
      value = (value === 'true' ? true : value === 'false' ? false : value);
      newObject[objKey] = value;
    });
  return newObject;
}
Olegdater
  • 2,381
  • 22
  • 20