Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string true/false to boolean in JSON response

Tags:

javascript

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.

like image 703
Chandra Kumar Perla Avatar asked Jun 16 '26 17:06

Chandra Kumar Perla


1 Answers

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);
like image 161
Slai Avatar answered Jun 19 '26 08:06

Slai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!