Title, this article lists some common transformation and processing methods in Web front-end development. Using JSON instead of strings is primarily for ease of handling.
Json:javascript Object Notation (JavaScript object Notation), JSON is actually a JavaScript object.
If there is no clear json, you can go to w3cschool understand http://www.w3school.com.cn/json/
1. Create a new string (JSON text) in JavaScript.
var txt = ' {' Employees ': [' + ' {' firstName ': ' Bill ', ' lastName ': ' Gates '}, ' + ' {' firstName ': ' George ', ' Lastnam E ":" Bush "}, ' + ' {" FirstName ":" Thomas "," LastName ":" Carter "}]} ';
Because JSON syntax is a subset of JavaScript syntax, the JavaScript function eval () can be used to convert JSON text to JavaScript objects.
The eval () function uses the JavaScript compiler to parse the JSON text and then generate the JavaScript object. You must enclose the text in parentheses in order to avoid syntax errors:
var obj = eval ("(" + txt + ")");
Note:The eval () function compiles and executes any JavaScript code. This hides a potential security issue.
Using the JSON parser to convert JSON to JavaScript objects is a safer practice. The JSON parser only recognizes JSON text and does not compile the script.
In the browser, this provides native JSON support, and the JSON parser is faster.
Native JSON support is included in newer browsers and the latest ECMAScript (JavaScript) standards.
String to JSON object: Json.parse (JSONSTR);
JSON object to JSON string: json.stringify (jsonobj);
JQuery method: JSON string to JSON object: Jquery.parsejson (JSONSTR);
<HTML><Body><H2>To create an object from a JSON string</H3><P>First Name:<spanID= "FName"></span><BR/>Last Name:<spanID= "LName"></span><BR/> </P> <Scripttype= "Text/javascript">vartxt= '{"Employees": [' +'{"FirstName": "Bill", "LastName": "Gates"},' +'{"FirstName": "George", "LastName": "Bush"},' +'{"FirstName": "Thomas", "LastName": "Carter"}]}'; obj=json.parse (TXT);d Ocument.getelementbyid ("fname"). InnerHTML=obj.employees[1].firstname document.getElementById ("lname"). InnerHTML=obj.employees[1].lastname</Script></Body></HTML>
2. How do you traverse the JSON array? It can be treated as an ordinary JavaScript object.
<HTML><Body><H2>How to traverse a JSON array</H3><DivID= "Result"></Div><Scripttype= "Text/javascript">vartxt= '[{"FirstName": "Bill", "LastName": "Gates"},' +'{"FirstName": "George", "LastName": "Bush"},' +'{"FirstName": "Thomas", "LastName": "Carter"}]';varArrayjson=json.parse (TXT);varHTML="'; for(varPinchArrayjson) {HTML+='FirstName:'+Arrayjson[p].firstname; HTML+='LastName'+Arrayjson[p].lastname; HTML+='<br/>'; }document.getelementbyid ("result"). InnerHTML=html;</Script></Body></HTML>
Interop and processing of JSON objects and strings