Harish Varma Harish Varma - 3 months ago 13
Node.js Question

How to convert boolean and number type Json Key value to string type

Iam having a json object where it has different key values of string,boolean and number type.I want to convert the boolean and number type key value to string type..i.e.,eg{"rent":2000,"isPaid":false} which is a valid json .Here i want to convert rent and isPaid to string type i.e.,{"rent":"2000","isPaid":"false"} which is also valid.for this Iam using replacer,but not working exactly how i require

var json={"rent":2000,"isPaid":false};
var jsonString = JSON.stringify(json, replacer);
function replacer(key, value) {
if (typeof value === "boolean"||typeof value === "number") {
return "value";
}
return value;
}
console.log(jsonString);


Then above code is consoling as {"rent":"value","isPaid":"value"}

Then I replaced return "value" with return '"'+value+'"' .Then on console it is giving {"rent":"\"2000\"","isPaid":"\"false\""}

So can someone help me so that it returns as {"rent":"2000","isPaid":"false"}..

Any help is apreciable..Thanks!

Answer

Try this:

var json={"rent":2000,"isPaid":false};
var jsonString = JSON.stringify(json, replacer);

function replacer(key, value) {
  if (typeof value === "boolean"||typeof value === "number") {
    return String(value);
  }
  return value;
}

console.log(jsonString);

We're using the String() function to convert your booleans and numbers to string. The output is:

{"rent":"2000","isPaid":"false"}
Comments