JSON has many empty values, where I want to replace the empty value with a default string.
var json= [
{
"machineNum": "1A",
"serialNo": "123",
"city": ""
},
{
"machineNum": "2B",
"serialNo": "",
"city": ""
},
{
"machineNum": "3A",
"serialNo": "123",
"city": "NewCity"
}
]
var newJson=json.replace("","Not AVailable");
console.log(newJson);
So wherever there is "" - empty value replace with default value "Not Available"
The above is not working.
JSFIDDLE here
You need to do a replace on the json string not a javascript object. Also you aren't looking for "" you are looking for "\"\"":
var json= [
{
"machineNum": "1A",
"serialNo": "123",
"city": ""
},
{
"machineNum": "2B",
"serialNo": "",
"city": ""
},
{
"machineNum": "3A",
"serialNo": "123",
"city": "NewCity"
}
]
var temp = JSON.stringify(json);
temp = temp.replace(/\"\"/g, "\"Not Available\"");
json = JSON.parse(temp);
console.log(json);
Console Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With