JavaScript implements four methods of converting strings to JSON objects


In many cases, we need to convert data into JSON format to make requests. Here are several ways to convert JSON to you.

1. JavaScript function eval()

grammar:

var obj = eval ("(" + txt + ")");  //必须把文本包围在括号中,这样才能避免语法错误 

eval() Definition: The eval() function evaluates a string and executes the JavaScript code in it.

Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert JSON text into JavaScript objects.

Note: When the string contains an expression, the eval() function will also be compiled and executed, and there will be security issues in the conversion.

2. Browser comes with object JSON, JSON.parse()

grammar:

var obj = JSON.parse(text[, reviver])
//text:必需, 一个有效的 JSON 字符串。解析前要确保你的数据是标准的 JSON 格式,否则会解析出错。
//reviver: 可选,一个转换结果的函数, 将为对象的每个成员调用此函数。

JSON.parse() is safer and faster than eval()
Supports major browsers: Firefox 3.5, IE 8, Chrome, Opera 10, Safari 4.

Note: IE8 compatibility mode, IE 7, IE 6, there will be compatibility issues.

3. jQuery plugin, $.parseJSON()

grammar:

var obj = $.parseJSON(json)  //json:String类型,传入格式有误的JSON字符串可能导致抛出异常

4. When ajax request gets json data, $.getJSON()

grammar:

jQuery.getJSON(url,data,success(data,status,xhr))
//url    必需。规定将请求发送的哪个 URL。
//data    可选。规定连同请求发送到服务器的数据。
//success(data,status,xhr)    可选。规定当请求成功时运行的函数。

At this time, the data returned is already a JSON object, and no further conversion is required.

$.getJSON() is a shorthand Ajax function equivalent to:

$.ajax({
    
    
  url: url,
  data: data,
  success: callback,
  dataType: "json"
});

Guess you like

Origin blog.csdn.net/qq_68862343/article/details/131522977