I'm studying some complex cases on json convert with js, and I have a situation like this:
I got this:
{
"page": "POST,PUT:122",
"news": "PUT"
}
And I want to convert to this:
{
"page": {
"POST": [
"POST"
],
"PUT": 122
},
"news": {
"PUT": [
"PUT"
]
}
}
I'm already doing this conversion on a revert case with this great solution by @RomanPerekhrest, I want to get back the same structure, but I tried a few ways with no success, Roman's solution:
var obj = {
"page": {
"POST": [
"POST"
],
"PUT": 122
},
"news": {
"PUT": [
"PUT"
]
}
};
Object.keys(obj).forEach(function (k) {
var innerKeys = Object.keys(obj[k]), items = [];
innerKeys.forEach(function(key) {
items.push((Array.isArray(obj[k][key]))? key : key + ":" + obj[k][key]);
});
obj[k] = items.join(",");
});
console.log(JSON.stringify(obj, 0, 4));
var obj = {
"page": "POST,PUT:122",
"news": "PUT"
};
var rez={};
Object.keys(obj).forEach(function(key){
obj[key].split(",").forEach(function(value){
var item = value.split(":");
var obj=rez[key] || {};
if (item.length>1){
obj[item[0]]=isNaN(Number(item[1])) ? item[1] : Number(item[1]);
rez[key]=obj;
}else{
obj[item[0]]=[item[0]];
rez[key]=obj;
}
});
});
console.log(rez);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments