Home > Article > Web Front-end > Parse and convert between JSON objects and strings
This article mainly provides a detailed introduction to the conversion between JSON objects and strings. Friends in need can come and refer to it. I hope it will be helpful to everyone
In the development process , if you need to pass a small number of parameters to the front and back, you can directly use the ajax data function, pass it in json format, and use the background Request. But sometimes, you need to pass multiple parameters, so that when the background
accepts Multiple requests are troublesome. At this time, they must be passed in the form of a class or a collection.
For example: the frontend passes JSON objects in class format:
var jsonUserInfo = "{\"TUserName\":\"" + userName + "\",\"TInterest \":\"" + interest + "\",\"TSex\":\"" + sex + "\",\"TCity\":\"" + city + "\",\"TDetail\" :\"" + detail + "\"}";
If the jsonUserInfo is spelled out without escape symbols, var jsonArrayFinal = JSON.stringify(jsonArray); needs to be converted before passing.
Copy the code as follows:
$.ajax(
# ,
data: { userInfo: jsonUserInfo, flag: "123456", key: "654321" },
dataType: "text",
success: function(data) {
pShow").html(data);
For example:
[{"name":"a"},{"name","b"},{"name","c"}], it cannot be passed and must be Use JSON.stringify to convert the array object into a string, and then pass it through AJAX.
For example, I have two variables. I want to convert a into a string and b into a JSON object:
var b='{"name":"Mike","sex":"female","age":"29"}';
In advanced browsers such as Firefox, chrome, opera, safari, ie9, ie8, etc., you can directly use the stringify() and parse() methods of the JSON object.
JSON.stringify(obj) converts JSON to string. JSON.parse(string) converts the string into JSON format;
The above conversion can be written as follows:
var a={"name":"tom","sex":"male", "age":"24"};
var aToStr=JSON .stringify(a);
var bToObj=JSON.parse(b);alert(typeof(aToStr)); //string
alert(typeof(bToObj));//object
JSON.stringify()
ie8 (compatibility mode), ie7 and ie6 do not have JSON objects, but
http://www.json.org/js.html
provides one json.js, so that ie8 (compatibility mode), ie7 and ie6 can support JSON objects and their stringify() and parse() methods; you can get this js at http://www.php.cn/, generally Now use json2.js.
var cToObj=eval("("+c+")"); alert(typeof(cToObj));
jQuery also has a method for converting strings to JSON format, jQuery.parseJSON(json), which accepts a JSON string in a standard format and returns a parsed JavaScript (JSON) object. Of course, if you are interested, you can encapsulate a jQuery extension yourself. jQuery.stringifyJSON(obj) converts JSON into a string. For more articles related to parsing and converting JSON objects and strings, please pay attention to the PHP Chinese website!