4

I want to transform a JSON formatted output to another. How I can do this?

Example: Old JSON

"data": 
[
    {
        "id" : "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
        "name" : "test"
    },
    {
        "id" : "ac310894-d808-447b-a189-d07edb7f6dd7",
        "name" : "test2"
    }
]

New JSON which I want without braces only like this with bracket

"aaData": 
[ 
    [
        "e49e183e-9325-4e62-8eda-7e63fb7cdbbd","test"
    ],
    [
        "ac310894-d808-447b-a189-d07edb7f6dd7","test2"
    ]
] 
Archmede
  • 1,592
  • 2
  • 20
  • 37
Sascha Heim
  • 301
  • 1
  • 4
  • 15
  • That's not quite valid as is - should there be a pair of curly braces around both old and new formats? – nnnnnn Jan 26 '12 at 10:18
  • i need exactly the second one with this brackets – Sascha Heim Jan 26 '12 at 10:21
  • 1
    The second format isn't valid JSON, so you can't use Javascript JSOn libraries. You could `JSON.stringify()` your JSON object and then do a string replace to replace all `{` with `[`. – Ayush Jan 26 '12 at 10:28
  • 4
    What I was saying is that the above isn't valid JSON unless it has curly brackets around the whole thing, but given that your accepted answer doesn't use JSON at all I guess you were trying to ask about JavaScript objects rather than JSON. – nnnnnn Jan 26 '12 at 10:37
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Liam Aug 25 '16 at 08:30

7 Answers7

10

You could just loop through the items and push them into a new object:

var len = old.data.length,
    newData = {aaData:[]},
    i;

for ( i=0; i < len; i+=1 ) {
    newData.aaData.push( [ old.data[ i ].id, old.data[ i ].name] );   
}

example: https://jsfiddle.net/q2Jzb/1/

You are presumably passing these to DataTables (as you use the name aaData), note that DataTables takes an object as the configuration, it's not the same as JSON.

Fishcake
  • 10,496
  • 7
  • 44
  • 72
Niklas
  • 29,752
  • 5
  • 50
  • 71
3

Just another answer using JSONata library:

What you want is easily achievable using the following:

$.[id, name]

For live demo look at: https://try.jsonata.org/UXYx6_xEh

human
  • 2,250
  • 20
  • 24
1

You can also use JSON Path and use the query ($..id) on your dataset yields exactly what you seem to be looking for. Checkout https://jsonpath.com/? and enter your data in the left hand box and $..id in the text box for JSONPath Syntax

Anu
  • 43
  • 9
1

Try the following;

function format(oldFormat) {
    var newFormat = [];

    oldFormat = oldFormat.data;

    for (var i=0;i<oldFormat.length;i++) {
        newFormat.push([oldFormat[i].id], oldFormat[i].name);
    };

    return {
        aaData: newFormat
    };
}

You'd then call use the function by;

var newStuff = format(varPointingToOldStuff);

The function expects to receive a JavaScript object rather than JSON, and returns a JavaScript object rather than JSON. Make sure you understand the differences between a JSON (string) and a JavaScript object.

You can convert a JSON string to a JavaScript object using JSON.parse(yourJsonString), and can convert a JavaScript object to a JSON string using JSON.stringify(yourJavaScriptObject).

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
1

You can use JavaScript to transform the input data into a new form of object and then use JSON JavaScript library (the JSON.stringify function, see more here http://www.json.org/js.html) to convert the newly created object into a proper JSON. The following code uses jQuery and the JSON library to solve your problem. Use of jQuery is purely optional, as well as there are other libraries to make JSON.

<pre id="code"></pre>

<script type="text/javascript">
    $(document).ready(function () {
        var old = { "data":
            [
                {
                    "id": "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
                    "name": "test"
                },
                {
                    "id": "ac310894-d808-447b-a189-d07edb7f6dd7",
                    "name": "test2"
                }
            ]
        };

        var newData = [];
        for (var i = 0, l = old.data.length; i < l; i++) {
            var o = old.data[i];
            newData[i] = [o.id, o.name];
        }
        $("#code").text(JSON.stringify(newData));
    });
</script>
Andrew Sklyarevsky
  • 2,095
  • 14
  • 17
0

JSONata in the right way !

Expresion:

{ "aaData": data.[id, name] }

Result:

{
  "aaData": [
    [
      "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
      "test"
    ],
    [
      "ac310894-d808-447b-a189-d07edb7f6dd7",
      "test2"
    ]
  ]
}

Run it on: https://try.jsonata.org/Pg51Kzp0c

Daniel De León
  • 13,196
  • 5
  • 87
  • 72
0

You could just do it as a string replace:

newJSON = oldJSON.replace(/"id" : |"name" : /g, "")
                 .replace(/{/g, "[").replace(/}/g, "]");

But that's kind of dodgy. The other way is to parse the JSON and then process the resulting object and then turn the result back into JSON:

var oldData = JSON.parse(oldJSON)["data"],
    aaData = [],
    arr,
    newJSON,
    i, k;

for (i = 0; i < data.length; i++) {
    arr = [];
    for (k in data[i])
       arr.push(data[i][k]);
    aaData.push(arr);
}

newJSON = JSON.stringify({ "aaData" : aaData });

Where oldJSON is the string with the old format from your question. (I've just looped through the properties in each array item rather than assuming they'll always have "id" and "name" properties.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241