The method of converting string (string) to json in JavaScript

JavaScript: convert string to json

the first method:

Use the js function eval();

testJson=eval(testJson); is the wrong conversion method.

The correct conversion method needs to add (): testJson = eval("(" + testJson + ")");

eval() is very fast, but he can compile and execute any javaScript program, so there will be security issues. Using eval(). The source must be trustworthy. A safer json parser needs to be used. If the server is not strictly encoded in json or if the input is not strictly validated, it is possible to provide invalid json or contain dangerous scripts, execute scripts in eval(), and release malicious code.

js code:

code show as below:

function ConvertToJsonForJs() {
  //var testJson = "{ name: '小强', age: 16 }";(支持)
  //var testJson = "{ 'name': '小强', 'age': 16 }";(支持)
  var testJson = '{ "name": "小强", "age": 16 }';
  //testJson=eval(testJson);//错误的转换方式
  testJson = eval("(" + testJson + ")");
  alert(testJson.name);
  }

The second method uses the jquery.parseJSON() method to have relatively high requirements on the format of json, which must conform to the format of json

jquery.parseJSON()
  js:代码
  代码如下:
  function ConvertToJsonForJq() {
  var testJson = '{ "name": "小强", "age": 16 }';
  //不知道
  //'{ name: "小强", age: 16 }' (name 没有使用双引号包裹)
  //"{ 'name': "小强", 'age': 16 }"(name使用单引号)
  testJson = $.parseJSON(testJson);
  alert(testJson.name);
  }

Many times we need to assemble strings into json objects, first combine strings, and then convert them into json objects

example:

var convertStringToJSON = function(){
    var str="{'ID':12,'Name':'Tom','Age':21}";
    var stu = eval('('+str+')');
    alert(stu.Name);
}

After the above code is executed, "Tom" will pop up, indicating that it has been successfully converted into a json object. 

Create XMLHTTPRequest:

<script language="javascript" type="text/javascript">
var request;
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }
  if (!request)
    alert("Error initializing XMLHttpRequest!");
}
function getCustomerInfo() {
  createRequest();
  // Do something with the request variable
}
</script>

Guess you like

Origin blog.csdn.net/cdming/article/details/130235193