Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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

share|improve this question
up vote 1 down vote accepted

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

share|improve this answer
    
It seems right @VladuIonut, but I need the '122' as a int (122) not as a string ("122"). :) – Lucas Santos Aug 2 at 14:49
    
all the values are integer? – Vladu Ionut Aug 2 at 14:51
    
I've update the snippet – Vladu Ionut Aug 2 at 14:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.