json syntax rules
The json syntax is a subset of the javascript object notation syntax.
•data in name/value pairs
•data are separated by commas
•Curly braces save objects
•square brackets save array
json object
The json object is written in curly braces:
An object can contain multiple name/value pairs:
{"firstname":"john", "lastname":"doe"}
This is easy to understand,Is equivalent to this javascript statement:
firstname="john"
lastname="doe"
json array
The 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 example above,The object "employees" is an array containing three objects.Each object represents a record about someone (with first and last names).
json file
The file type of the json file is ".json"
The mime type of the json text is "application/json"
json text to javascript object
The javascript function eval () can be used to convert json text into a javascript object.
The eval () function uses a javascript compiler that parses json text and generates a javascript object. Text must be enclosed in parentheses,This will prevent 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", // can be text, if text is used, the returned result is a string;
If you need json format, 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 object array via javascript
var employees=[
{"firstname":"bill", "lastname":"gates"},{"firstname":"george", "lastname":"bush"},{"firstname":"thomas", "lastname":"carter"}
];
Two ways to access javascript object properties
object.attribute
object ["attribute"]
E.g:
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
Related articles
- Detailed introduction of json object in js
- Interchange and processing skills between JSON object and String in JS
- JSON--List collection into JSON object
- Jquery method for dynamically traversing properties and values of Json object
- Javascript object json array json string mutual conversion and value method