0

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));

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

It seems right @VladuIonut, but I need the '122' as a int (122) not as a string ("122"). :)
all the values are integer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.