4

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"
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Govinda Totla
  • 576
  • 6
  • 19
  • 2
    You could pass the numbers `1` and `0` instead, which [normally](https://stackoverflow.com/questions/2764017/is-false-0-and-true-1-an-implementation-detail-or-is-it-guaranteed-by-the) equal `true` and `false` in *Python*. In Javascript you can turn booleans into numbers using `+boolean` like `+true`. – Lain Aug 07 '20 at 07:15
  • I know a way. But not a efficient way. – felix Aug 07 '20 at 07:16
  • @Lain I thought of that but that is not what I ideally want as when it gets printed it prints 0 and 1 which is not good. I want it to print either (True/False) or ("true"/"false"). – Govinda Totla Aug 07 '20 at 07:18
  • You'll have to transform the object into a new one with strings – Liam Aug 07 '20 at 07:23
  • The problem is that {"value": False} is not a valid JSON – Giovanni Esposito Aug 07 '20 at 07:26

1 Answers1

6

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));
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73