最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Transform JSON Object to another - Format It - Stack Overflow

programmeradmin4浏览0评论

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"
    ]
] 

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"
    ]
] 
Share Improve this question edited May 19, 2022 at 0:42 Archmede 1,8423 gold badges24 silver badges41 bronze badges asked Jan 26, 2012 at 10:11 Sascha HeimSascha Heim 3131 gold badge4 silver badges15 bronze badges 5
  • That's not quite valid as is - should there be a pair of curly braces around both old and new formats? – nnnnnn Commented Jan 26, 2012 at 10:18
  • i need exactly the second one with this brackets – Sascha Heim Commented Jan 26, 2012 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 Commented Jan 26, 2012 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 Commented Jan 26, 2012 at 10:37
  • Possible duplicate of Access / process (nested) objects, arrays or JSON – Liam Commented Aug 25, 2016 at 8:30
Add a comment  | 

7 Answers 7

Reset to default 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.

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

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

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

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

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>

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

发布评论

评论列表(0)

  1. 暂无评论