3

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.

8
  • 3
    Please post your attempts. Commented Jul 15, 2018 at 5: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 and Array methods may help here as well. Commented Jul 15, 2018 at 5:45
  • 2
    Possible duplicate of How can I convert a string to boolean in JavaScript? Commented Jul 15, 2018 at 5:45
  • @Xufox No, this is aleardy a valid object, not a string. Commented Jul 15, 2018 at 6:10
  • 1
    There are no absolute same questions on the site, but the above mentioned topic aswer how to cast object fields to boolean ,@חייםפרידמן Commented Jul 15, 2018 at 6:21

4 Answers 4

13

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about the reviver function. This is pretty cool, and an alternative (And works recursively!).
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);

1 Comment

As stated in his original question "My JSON response is very huge with many objects and arrays.". This answer does not satisfy that.
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);

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.