简体   繁体   中英

Building a json tree structure

I will be passing a json string to a servlet via an ajax request :

function add() {
    $.ajax({
    url: "pathToServlet" ,
    dataType: "text",
    data: ({
        name : 'myJsonString'
    }),
    success: function(data) {
            alert('returned!!');
    });
}

To build up this json string I have a listener which when fired appends a new piece of json to string :

var json = "";
json += "{ new json ..... }"

Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?

What I would recommend doing is building up an object , and then when you're ready to send it to the server, serialize the object via JSON.stringify .

So for instance, you might have an object called data :

var data = {};

...to which you might periodically add properties:

data.foo = "bar";
data.stuff = {nifty: "stuff"};

Or perhaps data is an array:

var data = [];

...to which you add things:

data.push({nifty: "stuff"});

Then, when you're ready to send it:

function add() {
    $.ajax({
    url: "<%=savePortlet%>" ,
    dataType: "text",
    data: {
        name : JSON.stringify(data)
    },
    success: function(data) {
            alert('returned!!');
    });
}

Because you're passing an object into ajax , you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.

JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page .

If using jQuery you can use jquery-json , a really handy plugin to handle JSON with JavaScript and jQuery.

Usage:

var jsonString = $.toJSON(myObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM