Json object and array and simple implementation method for converting to js object, jsonjs
JSON syntax rules
JSON syntax is a subset of the syntax of JavaScript Object Notation.
• Data in name/value pairs
• Data is separated by commas (,).
• Brackets save objects
• Square brackets Save the Array
JSON object
JSON objects are written in curly brackets:
The object can contain multiple name/value pairs:
{ "firstName":"John" , "lastName":"Doe" }
This is easy to understand and is equivalent to this JavaScript statement:
firstName = "John"lastName = "Doe"
JSON Array
JSON array is written in square brackets:
An array can contain multiple objects:
{ "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
In the preceding example, the object "employees" is an array containing three objects. Each object represents a record about someone (with a surname and a name.
JSON File
• The JSON file type is ". json"
• The MIME type of JSON text is "application/json"
Convert JSON text to JavaScript Object
The JavaScript function eval () can be used to convert JSON text to JavaScript objects.
The eval () function uses a JavaScript compiler that parses JSON text and generates JavaScript objects. Text must be enclosed in parentheses to avoid syntax errors:
Var obj = eval ("(" + jsontxt + ")");
Example:
$. Ajax ({type: 'post', url: '.../caseHandler. ashx? Action = GetCase & id = '+ id. toString (), // url action is the method name data: "", dataType: "text", // It Can Be text. If text is used, the returned result is a string; if json format is required, you can set it to json ContentType: "application/json; charset = UTF-8", success: function (returnedData) {getMarkerFeature (eval ("(" + returnedData + ")") ;}, error: function (msg) {alert ("Access failed: "+ msg );}});
Create an object array using JavaScript
var employees = [{ "firstName":"Bill" , "lastName":"Gates" },{ "firstName":"George" , "lastName":"Bush" },{ "firstName":"Thomas" , "lastName": "Carter" }];
Two methods for accessing JavaScript Object Attributes
Object. attribute
Object ["attribute"]
For example:
Var employees = [{"firstName": "Bill", "lastName": "Gates" },{ "firstName": "George", "lastName": "Bush "}, {"firstName": "Thomas", "lastName": "Carter"}]; alert (employees [0]. lastName); // method 1 alert (employees [0] ["lastName"]); // method 2
The above is all the content of the simple implementation methods for json objects and arrays and converting them into js objects. I hope you can support more help ~