Reputation: 640
I'am 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 I'am 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 appreciable! Thanks!
Upvotes: 3
Views: 10768
Reputation: 32
There is some reference, using JSON.parse(text[, reviver])
"reviver" parameter.
let reviver = (key, value) => (typeof value === 'number' || typeof value === 'boolean') ? String(value) : value;
Upvotes: 0
Reputation: 631
You can use JavaScript's toString()
method to convert numbers/boolean to change them to string, as below:
var json={"rent":2000,"isPaid":false};
var temp = {};
json.forEach(function(val, key)
{
temp[key] = val.toString();
});
json = temp;
Upvotes: 0
Reputation: 6232
You can do it by this way...
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=""+value+"";
}
return value;
}
console.log(jsonString);
Upvotes: 1
Reputation: 154
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"}
Upvotes: 7