I am facing a challenge with a nested JSON object that requires me to iterate through its keys. The tricky part is that each key's value could be a String, a JSON array, or another JSON object. In order to perform different operations based on the type of object, I need to determine if it is a String, a JSON object, or a JSON array.
Although I attempted using typeof
and instanceof
, neither method proved successful. typeof
incorrectly identifies both JSON objects and arrays as 'object', while instanceof
throws an error when I try to use it with obj instanceof JSON
.
After parsing the JSON into a JavaScript object, I am seeking a way to ascertain whether it is a regular string, an object with keys and values (from a JSON object), or an array (from a JSON array).
For instance:
JSON
var data = "{'hi':
{'hello':
['hi1','hi2']
},
'hey':'words'
}";
Sample JavaScript
var jsonObj = JSON.parse(data);
var path = ["hi","hello"];
function check(jsonObj, path) {
var parent = jsonObj;
for (var i = 0; i < path.length-1; i++) {
var key = path[i];
if (parent != undefined) {
parent = parent[key];
}
}
if (parent != undefined) {
var endLength = path.length - 1;
var child = parent[path[endLength]];
//if child is a string, add some text
//if child is an object, edit the key/value
//if child is an array, add a new element
//if child does not exist, add a new key/value
}
}
How can I effectively conduct the object checking process showcased above?