Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON replace all empty values with a default string

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

like image 439
monda Avatar asked Mar 04 '26 06:03

monda


1 Answers

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:

enter image description here

like image 89
brso05 Avatar answered Mar 06 '26 21:03

brso05



Donate For Us

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