0

I have a question regarding JSON. I am using a jquery plugin which expected JSON structure as below :

[   { key: "Id" },
            { key: "Username" },
                    { key: "Age" }
        ], 

but my JSON looks like :

    [{
        "Employee1": 
        {
          "ID": 43036,
          "Name": XYZ,
          "Age": 21
        },
       "Employee2": 
        {
          "ID": 30436,
          "Name": MNP,
          "Age": 23
        }
    }]

Now I don't want to change my code, is there any solution so that I can pass Id , Name to my plugin json without using "Employee". I need my JSON as :

[        
        {
          "ID": 43036,
          "Name": XYZ,
          "Age": 21
        }, 
        {
          "ID": 30436,
          "Name": MNP,
          "Age": 23
        }
    ]

Thanks in Advance

Haseeb Akhtar
  • 1,233
  • 3
  • 16
  • 32
  • I don't really get what you're asking. Do you want to convert the second JSON string to the format of the first, or do you want to use the object created by the second JSON string to create a new JSON object that's in the correct format? – Anthony Grist Apr 27 '12 at 15:03
  • I am stuck at "I have a question regarding JSON", nothing more makes any sense... Can you explain what you want? Do you just want the keys alone? Most likely duplicate of http://stackoverflow.com/questions/18912/how-to-find-keys-of-a-hash – Selvakumar Arumugam Apr 27 '12 at 15:05
  • Yes actually plugin needs only key which is in example is Id , Name and Age. and it generates a grid by using these values but in my json a parent key (Employee) coming with each Id, name . I want json looks like [{ "ID": 43036, "Name": XYZ, "Age": 21 },{ "ID": 30436, "Name": MNP, "Age": 23 } ] – Haseeb Akhtar Apr 27 '12 at 15:08

2 Answers2

0

Something like this?

var myObj = [{
        "Employee1": 
        {
          "ID": 43036,
          "Name": XYZ,
          "Age": 21
        },
       "Employee2": 
        {
          "ID": 30436,
          "Name": MNP,
          "Age": 23
        }
    }];

var jsonObj = [];
$.each(myObj[0], function(key, val){
     jsonObj.push({ key: val.ID });
     jsonObj.push({ key: val.Name });
     jsonObj.push({ key: val.Age });
}); 
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

What you need a simple function to push the values inside the object,

var data = [{
    "Employee1": {
        "ID": 43036,
        "Name": 'XYZ',
        "Age": 21
    },
    "Employee2": {
        "ID": 30436,
        "Name": 'MNP',
        "Age": 23
    }}];

data = data[0];
var output = [];
for (i in data) {
    output.push(data[i]);
}

DEMO

Note: The JSON you posted was invalid, XYZ and MNP are string values and I suppose the other numbers too.. I leave the validation to you.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134