What I am hoping achieve is to use recursion or other method to dynamically create a specific output based on the json input. Below is just an example of some json and the format I hope to accomplish.
"id": "0001",
"type": "donut",
"name": "Cake",
"image": [
{
"url": "images/0001.jpg",
"width": 200,
"height": 200
},
{
"url": "images/0002.jpg",
"width": 300,
"height": 300
}
],
"thumbnail": {
"url": "images/thumbnails/0001.jpg",
"width": 32,
"height": 32
}
}
Build an array of the keys using the following format.
["id","type","name","image[0].url","image[0].width","image[0].height","image[1].url","image[1].width","image[1].height","thumbnail.url","thumbnail.width","thumbnail.height"]
After building the array I would like to then iterate through the array and build a string like follows.
[ "id" ; $id ; JSONString ];[ "type" ; $type ; JSONString ];[ "name" ; $name ; JSONString ];[ "image[0].url" ; $image.url[0] ; JSONString ];[ "image[0].width" ; $image.width[0] ; JSONString ];[ "image[0].height" ; $image.height[0] ; JSONString ];[ "image[1].url" ; $image.url[1] ; JSONString ]...
So far I have been able to get this working on fairly simple JSON but have failed to get anything I have tried working with more complex structures.
JS Code : Edited
var json = '{"id":"0001","type":"donut","name":"Cake","image":[{"url":"images/0001.jpg","width":200,"height":200},{"url":"images/0002.jpg","width":300,"height":300}],"thumbnail":{"url":"images/thumbnails/0001.jpg","width":32,"height":32}}';
var obj = JSON.parse(json);
// Recursion through the json
function getKeys(object) {
return Object
.entries(object)
.reduce((r, [k, v]) =>
r.concat(v && typeof v === 'object'
? getKeys(v).map(sub => [k].concat(sub))
: k
),
[]
);
}
function buildFM(object) {
var objLength = object.length;
var i = 1;
var str = '';
for (x of object) {
var nodes = x.split(/\.(?=[^\.]+$)/);
if (i == objLength) {
str += '[ "' + x + '" ; $' + nodes[nodes.length - 1] + ' ; JSONString ]';
} else {
str += '[ "' + x + '" ; $' + nodes[nodes.length - 1] + ' ; JSONString ] ; ';
}
i++;
}
return str;
}
// Result from Recursion
result = getKeys(obj);
console.log(result);
// Setup Map of JSON for creating FM function
var fmMap;
fmMap = result.map(a => a.join('.'));
console.log(fmMap);
// Build FM Elements
var fmFX = '';
var fmFX = buildFM(fmMap);
console.log(fmFX);
Using the following JSON this method works fine.
var json = '{"fieldData":{"City":"New York","FirstName":"John","ID":"001","LastName":"Doe","State":"NY","Zip":"10005"}}';
On the more complex examples I have tried I get the following error.
Error:
Uncaught TypeError: a.join is not a function
at jsonRecursion.html:216
at Array.map (<anonymous>)
at jsonParsing.html:216
How do I handle more complex json to get the array of keys like exampled?