0

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?

Geronimo
  • 461
  • 5
  • 23

1 Answers1

1

Here is a sample of a function that prints all the key : value for all objects recursively

function readJsonObject(jsonObject) {

  if (Array.isArray(jsonObject)) {
    for (var el of jsonObject) {
      readJsonObject(el)
    }
    return
  } 

  else if (typeof jsonObject === 'object' && jsonObject.constructor === Object) {
    for (var key of Object.keys(jsonObject)) {
      var value = jsonObject[key];
      var toDisplay;

      if (value && typeof value === 'object' && value.constructor === Object) {
        toDisplay = readJsonObject(value);
      } else if (Array.isArray(value)) {
        toDisplay = JSON.stringify(value);
        readJsonObject(value);
      } else {
        toDisplay = value;
      }
      console.log(key + ": " + toDisplay);
    }
  }

  return jsonObject;
}

    
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":null },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}'; 

var obj = JSON.parse(text);

console.log(readJsonObject(obj))

I handled Arrays as a special type, but please note there are other types that you maybe should check, since object encapsulate many other types, for instance null.

madjaoue
  • 5,104
  • 2
  • 19
  • 31