3

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

1
  • It could work if you used it on the JSON string, and not the parsed JSON object. Commented Jul 2, 2015 at 12:32

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

it is replacing the first occurrence of "" (empty). other remains "" (empty) instead of Not Available.
You could use the global modifier for the regex. Replace this line:>> temp = temp.replace(/""/g, "\"Not Available\"");
Nice answer, +1
3

If you don't want to stringify/reparse the json, you could loop over the array and each property of the objects in the array.

json.forEach(function (machine) {
    Object.keys(machine).forEach(function (key) {
        if (machine[key] === '' && machine.hasOwnProperty(key)) machine[key] = 'Not Available';
    });
});

Comments

1

You can use Array.prototype.map along with Object.keys to make sure all key-value pairs which have empty value are all applied with default string. See a quick example below:

function replaceEmpty(json, defaultStr){
    return json.map(function (el){
        Object.keys(el).forEach(function(key){
            el[key] = el[key] || defaultStr;
        });
        return el;
    });
}

var result = replaceEmpty(json,"Not Available");

Output

[{"machineNum":"1A","serialNo":"123","city":"Not Available"},{"machineNum":"2B","serialNo":"Not Available","city":"Not Available"},{"machineNum":"3A","serialNo":"123","city":"NewCity"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.