I received a JSON response that looks like this:
{
"data":[
{
"type":"node--base_product_coffee",
"id":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45918",
"date":"1990",
"data1":[
{
"type1":"product_coffee1",
"id1":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45777",
" date1 ":[
{
" res ":" oui "
},
{
" res ":" non "
}
]
},
{
"type1":"product_coffee2",
"id1":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45666",
"date1":[
{
" res ":" ouiii "
},
{
" res ":" nonnn "
}
]
}
]
}
]
}
My objective is to extract values from a dynamic path such as data.data1.date1.res
in order to retrieve the result ['oui', 'non', 'ouiii', 'nonnn']
To achieve this, I have created the following function:
parseIt = function(response, s) {
if (!response) return null;
if (!s) return obj;
var data = Array.isArray(response) ? JSON.parse(JSON.stringify(response)) : JSON.parse(response);
var result = [];
var path = s.split('.');
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (getType(data[i][path[0]]) == 'string') {
result.push(data[i][path[0]]);
} else {
parseIt(data[i][path[i]], path.slice(1).join('.'));
}
}
} else {
for (var p in data) {
if (getType(data[p]) == 'string') {
result.push(data[p]);
} else {
parseIt(data[p], path.slice(1).join('.'));
}
}
}
document.writeln('result=>' + result + '</br>');
return result;
}
document.writeln(parseIt(response2, 'data.data1.date1.res')+'</br>');
//Console Output
result=>oui,non
result=>
result=>
result=>
However, I am encountering two issues:
- I am only getting results for the elements of date1.res ('oui' and 'non'), but I need all its elements ('oui', 'non', 'ouiii', 'nonnn')
- The result array is empty (how can I store results in a list when using recursion)
Your assistance is greatly appreciated, as I require this functionality for my work with complex JSON data.