0

I have a generated JSON file that I would like to transform. Is there an easy way to transform the "id"/"value" form of this JSON to a proper key/value JSON object, without using any frameworks?

 
These lines:

     "value":"chrome",
     "id":"foo"

would convert to:

  "foo": "chrome"

Input JSON:

{"row":[
    {
        "column":[
            {
                "value":"chrome",
                "id":"foo"
            },
            {
                "value":0,
                "id":"bar"
            },
            {
                "value":"baz1",
                "id":"baz"
            },
            {
                "value":0,
                "id":"legacy"
            }
        ]
    },
    {
        "column":[
            {
                "value":"firefox",
                "id":"foo"
            },
            {
                "value":0,
                "id":"bar"
            },
            {
                "value":"baz2",
                "id":"baz"
            },
            {
                "value":0,
                "id":"legacy"
            }
        ]
    }
]
}

Desired JSON:

{"row":[

    {
        "foo":"chrome",
        "bar":0,
        "baz":"baz1",
        "legacy":0
    },
    {
        "foo":"firefox",
        "bar":0,
        "baz":"baz2",
        "legacy":0
    }
]
}
  • Nope, there isn't. There is only the "hard" way - writing the code. – Diodeus - James MacFarlane Jun 19 '12 at 17:49
  • 1
    This can be done without any framework by simply traversing the object (parsed from the JSON) and change the structure accordingly. Whether this is considered easy or not is subjective. I think it's quite straightforward. – Felix Kling Jun 19 '12 at 17:51

2 Answers2

0

Here is the solution:

var result = {"row": []}

for (var i = 0; i < input["row"].length; i++) {
  var object = {};
  var column = input["row"][i]["column"];

  for (var j = 0; j < column.length; j++) {
    object[column[j]["id"]] = column[j]["value"];
  }

  result.row.push(object);
}

console.log(result);

input variable refers to your initial JSON object.

var input = {"row":[
    {
        "column":[
    ...
ioseb
  • 16,625
  • 3
  • 33
  • 29
0

here is my function, i was typing it out allready before ioseb posted his answer so i figured it post it as well, it's linted and everything

function transform(data) {
    "use strict";
    var x, i, row, column, colNumb, out = {rows : []}, rownum = data.row.length;
    for (x = 0; x < rownum; x += 1) {
        row = {};
        column = data.row[x].column;
        colNumb = column.length;
        for (i = 0; i < colNumb; i += 1) {
            row[column[i].id] = column[i].value;
        }
        out.rows.push(row);
    }
    return out;
}
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99