json (javascript object notation) is a lightweight data format,In a language-independent text format,Is the ideal data exchange format.At the same time, json is a javascript native format,This means processing json data in javascript

Basic format:

varjsondata="{" data1 ":" hello, "," data2 ":" world! "}"

Call methods jsondata.data1, jsondata.data2

A lot of json data is stored in an array

var jsondata=[
 {"name":"lilei", "age":19, "sex":"male"}, {"name":"hanmei", "age":18, "sex":"famale"}

Calling methodjsondata [0] .name, jsondata [1] .sex

Overall,json is relatively easy to understand and use,But there are many pitfalls at the same time,It's easy to fall in if you don't pay attention.

JSON parsing method

There are two types of json parsing methods:eval () and json.parse (), which are used as follows:

var jsondata="{" data1 ":" hello, "," data2 ":" world!} ";
var evaljson=eval ("(" + jsondata + ")");
var jsonparsejson=json.parse (jsondata);

This converts the json format string into a json object.

The differences between the two are as follows:

var value=1;
var jsonstr="{" data1 ":" hello "," data2 ":++ value}";
var data1=eval_r ("(" + jsonstr + ")");
console.log (data1);//At this time, the value is 2
var data2=json.parse (jsonstr);
console.log (data2);//Error reported

You can see the results of the control output table,The first eval () executes smoothly,The second is wrong.It is obvious from the above example,When eval parses a string,Will execute the code in that string (the consequences are pretty bad),As in the example above,The original value changed due to parsing a json string with eval.

Warning:Note about json and eval:It is dangerous to use eval in your code,Especially when using it to execute third-party json data (which may contain malicious code), use the json.parse () method to parse the string itself whenever possible.This method can catch syntax errors in json,And allows you to pass in a function,Used to filter or transform parsing results.If this method is supported by firfox 3.5, ie8 and safari 4 natively.The json parsing code included in most JavaScript libraries will directly call the native version.If there is no native support,Will call a slightly less powerful non-native version to handle.

  • Previous Interpretation of CI framework source code using Hookphp file to complete function expansion
  • Next Sample code of redis cache related operation files in CI framework