Parse the conversion between JSON objects and strings

  • 2020-03-30 00:58:09
  • OfStack

In the process of development, if a small number of parameters of the front and back end of the transfer, you can directly use the ajax data function, according to json format, the background Request can be, but sometimes, need to pass more than one parameter, so the background

It is troublesome to accept multiple requests, which should be passed in the form of a class or a collection.


For example, the foreground passes JSON objects in a class format:

Var jsonUserInfo = "{\" TUserName \ ": \" "+ userName +" \ ", \ "TInterest \" : \ "" + interest +" \ ", \ "TSex \" : \ "" + sex +" \ ", \ "TCity \" : \ "" + city +" \ ", \ "TDetail \" : \ "" + detail +" \ "} ";

Var jsonArrayFinal = json.stringify (jsonArray); Convert and then pass.


$.ajax(
                    {
                        type: "post",
                        url: "ReceiveHandler1.ashx",
                        data: { userInfo: jsonUserInfo, flag: "123456", key: "654321" },
                        dataType: "text",
                        success: function(data) {
                            $("#divShow").html(data);
                        }
 });

If the foreground passes a JSON array in multiple class formats, that is, the collection type:

Such as:

[{"name":"a"},{"name","b"},{"name"},{"name","c"}], cannot be passed, at this point must use json.stringify to convert the array object to a string, then AJAX pass.

For example, if I have two variables, I want to convert a to a string and b to a JSON object:

Var a = {" name ":" Tom "and" sex ", "male", "age" : "24"};
Var b = '{" name ":" Mike ", "sex", "female", "age" : "29"} ";

The stringify() and parse() methods of JSON objects can be used directly in advanced browsers such as Firefox, chrome, opera, safari, ie9, ie8, and so on.

Json.stringify (obj) converts JSON to a string. Json.parse (string) converts the string to JSON format;

The above transformation can be written like this:
Var a = {" name ":" Tom "and" sex ", "male", "age" : "24"};
Var b = '{" name ":" Mike ", "sex", "female", "age" : "29"} ";
Var aToStr = JSON. Stringify (a);
Var bToObj = JSON. Parse (b);
Alert (typeof (aToStr));   / / the string
Alert (typeof (bToObj)); / / object

JSON. Stringify ()

Ie8 (compatibility mode),ie7, and ie6 can use eval() to convert strings into JSON objects,

Var c = '{" name ":" Mike ", "sex", "female", "age" : "29"} ";
Var cToObj = eval (" (" c + + ") ");
Alert (typeof (cToObj));

JQuery also has a method for converting strings to JSON, jquery.parsejson (JSON), which takes a standard JSON string and returns a parsed JavaScript (JSON) object. Of course, you can wrap a jQuery extension yourself if you're interested, jquery.stringifyjson (obj) converts JSON to a string.


Related articles: