如何有效地对所有 Javascript 布尔值进行字符串化?

Gov*_*tla 4 javascript javascript-objects

我正在尝试将 javascript 对象发送到仅接受 python 布尔值(真/假)并拒绝 javascript 布尔值(真/假)的 POST API。我想将 JS 对象中存在的所有布尔值转换为字符串(“true”/“false”)。

有没有一种有效的方法来做到这一点?

输入 -

const a = {
  b: {
    c: 1,
    d: true
  },
  e: true
}
Run Code Online (Sandbox Code Playgroud)

输出 -

const a = {
  b: {
    c: 1,
    d: "true"
  },
  e: "true"
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ens 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));
Run Code Online (Sandbox Code Playgroud)