Govinda Totla
Govinda Totla

Reputation: 606

How to efficiently stringify all Javascript booleans?

I am trying to send a javascript object to a POST API which only accepts python Booleans(True/False) and rejects javascript booleans(true/false). I want to convert all the booleans present in JS object to strings ("true"/"false").

Is there an efficient way to do this?

Input -

const a = {
  b: {
    c: 1,
    d: true
  },
  e: true
}

Output -

const a = {
  b: {
    c: 1,
    d: "true"
  },
  e: "true"
}

Upvotes: 4

Views: 1040

Answers (1)

Mark Baijens
Mark Baijens

Reputation: 13222

You can add a replacer function as a second parameter to the stringify method to alter the way values are converted.

const a = {
  b: {
    c: 1,
    d: true
  },
  e: true
};

function replacer(key, value) {
  if (typeof value === 'boolean') {
    return value ? 'True' : 'False';
  }
  return value;
}

console.log(JSON.stringify(a, replacer));

Upvotes: 6

Related Questions