serializing to json in jquery

Question!

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...


Answers

The best way is to include the polyfill for JSON object.

But if you insist create a method for serializing an object to JSON notation (valid values for JSON) inside the jQuery namespace, you can do something like this:

Implementation

// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function (global, $) {
    var _PRIMITIVE, _OPEN, _CLOSE, _iterator, _stringify;

    if (global.JSON && typeof JSON.stringify === "function")
        return JSON.stringify;

    _PRIMITIVE = /string|number|boolean|null/;

    _OPEN = {
        object: "{",
        array: "["
    };

    _CLOSE = {
        object: "}",
        array: "]"
    };

    //creates the closure
    _iterator = function (items) {
        return function iterator (key, value) {
            var type = $.type(value),
                prop = "";

            //key is not an array index
            if (typeof key !== "number") {
                prop = '"' + key + '":';
            }
            if (type === "string") {
                prop += '"' + value + '"';
            }
            else if (_PRIMITIVE.test(type)) {
                prop += value;
            }
            else if (type === "array" || type === "object") {
                prop += _stringify(value, type);
            }
            else return;
            items.push(prop);
        }
    };

    //internal implementation
    _stringify = function (obj, type) {
        var items = [];
        //let the closure take place
        $.each(obj, _iterator(items));
        return _OPEN[type] + items.join(",") + _CLOSE[type];
    };

    return function stringify() {
        if (!arguments.length) return "";
        var obj = arguments[0],
            type = $.type(obj);
        //if obj is a primitive value
        if (_PRIMITIVE.test(type))
            return (obj === null ? "null" : obj.toString());
        //obj is array or object
        return _stringify(obj, type);
    }
}(window, jQuery));

Usage

var myObject = {
    "0": null,
    "total-items": 10,
    "undefined-prop": void(0),
    sorted: true,
    images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
    position: { //nested object literal
        "x": 40,
        "y": 300,
        offset: [{ top: 23 }]
    },
    onChange: function() { return !0 },
    pattern: /^bg-.+\.(?:png|jpe?g)$/i
};

var json = jQuery.stringify(myObject);
console.log(json);
By : jherax


Yes, you should JSON.stringify and JSON.parse your "Json_PostData" before calling $.ajax

   $.ajax({
            url:    post_http_site,  
            type: "POST",         
            data:   JSON.parse(JSON.stringify(Json_PostData)),       
            cache: false,
            error: function (xhr, ajaxOptions, thrownError) {
                alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );    
            },
            success: function (data) {
                alert("write json item, Ajax  OK");

            } 
    });
By : bruce


Its basically 2 step process :

First you need to stringify Like this var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);

After this you need to convert the string in Object var obj = JSON.parse(JSON_VAR);



This video can help you solving your question :)
By: admin