The example in this article describes the method of js reading and parsing JSON type data. Share it with everyone for your reference, the details are as follows:
1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data exchange format that uses a completely language-independent text format. It is an ideal data exchange format. At the same time, JSON is a JavaScript native format.
Very suitable for interaction between server and JavaScript
2. Why use JSON instead of XML
They all say this: Although there is a lot of publicity about how XML has cross-platform and cross-language advantages, however, unless applied to Web Services, in ordinary Web applications, developers often struggle with XML parsing It’s a headache. Whether the server generates or processes XML, or the client uses JavaScript to parse XML, it often leads to complex code and extremely low development efficiency. In fact, for most web applications, they do not need complex XML to transmit data at all, the extensibility of XML rarely has an advantage, and many AJAX applications even directly return HTML fragments to build dynamic web pages. Compared to returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but also lacks a certain degree of flexibility
3. How to use
The following code is an HTML code snippet, which allows you to click a button to parse json format data and alert the content
var json = { contry:{ area:{ man:"12万", women:"10万" } } }; //方式一:使用eval解析 var obj = eval(json); alert(obj.constructor); alert(obj.contry.area.women); //方式二:使用Funtion函数 var strJSON = "{name:'json name'}";//得到的JSON var obj = new Function("return" + strJSON)();//转换后的JSON对象 alert(obj.name);//json name alert(obj.constructor); //复杂一点的json数组数据的解析 var value1 = [ {"c01":"1","c02":"2","c03":"3","c04":"4","c05":"5","c06":"6","c07":"7","c08":"8","c09":"9"}, {"c01":"2","c02":"4","c03":"5","c04":"2","c05":"8","c06":"11","c07":"21","c08":"1","c09":"12"}, {"c01":"5","c02":"1","c03":"4","c04":"11","c05":"9","c06":"8","c07":"1","c08":"8","c09":"2"} ]; var obj1 = eval(value1); alert(obj1[0].c01); //复杂一点的json的另一种形式 var value2 = { "list":[ {"password":"1230","username":"coolcooldool"}, {"password":"thisis2","username":"okokok"} ], "array":[ {"password":"1230","username":"coolcooldool"}, {"password":"thisis2","username":"okokok"} ] }; var obj2 = eval(value2); alert(obj2.list[0].password); }
4. eval
① This form will significantly reduce performance because it must run the compiler
② The eval function also weakens the security of your application because it gives too much power to the text being evaluated. Just like the way the with statement executes, it slows down the performance of the language
③ The Function constructor is another form of eval, so it should also be avoided.
I hope this article will be helpful to everyone in JavaScript programming.