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);
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"}