I am trying to read a nested object as a key-value. I am using a recursive function to be able to enter each object and print its key-value. The problem is when I try to read a key-value where the value is null. It simply prints null, as if the key did not exist.
function readJsonObject(jsonObject){
for(var key in jsonObject){
if (typeof jsonObject[key] === 'object') {
readJsonObject(jsonObject[key]);
} else{
console.log(key + ": " + jsonObject[key]);
}
}
};
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":null },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj = JSON.parse(text);
readJsonObject(obj);
I should print:
firstName: John
lastName: null
firstName: Anna
lastName: Smith
firstName: Peter
lastName: Jones
But prints:
firstName: John
firstName: Anna
lastName: Smith
firstName: Peter
lastName: Jones
(Note that John's last name is not printed)
Any idea?