Simple implementation of json objects and arrays and converting them into js objects
- 2021-06-29 10:17:21
- OfStack
JSON grammar rules
JSON grammar is a subset of JavaScript object representation French.
&8226;Data in name/value pairs
&8226;Data is separated by commas
&8226;Curly brackets to save objects
&8226;Square brackets hold arrays
JSON object
The JSON object is written in curly brackets:
Objects can contain multiple name/value pairs:
{ "firstName":"John" , "lastName":"Doe" }
This is also easy to understand, equivalent to this JavaScript statement:
firstName = "John"
lastName = "Doe"
JSON Array
The JSON array is written in square brackets:
The 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 of three objects.Each object represents a record of someone (with a first and last name).
JSON file
&8226;The file type of the JSON file is'.json'
&8226;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 to an JavaScript object.
The eval() function uses the JavaScript compiler, parses the JSON text, and generates the JavaScript object.You must enclose the text in parentheses to avoid grammatical errors:
var obj = eval ("(" + jsontxt + ")");
Example:
$.ajax({
type: 'POST',
url: '../../caseHandler.ashx?action=GetCase&id=' + id.toString(), //url action Is the name of the method
data: "",
dataType: "text", // Can be text If you use text , returns a string;if necessary json Formatted, can be set 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 from 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"]
For example:
var employees = [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName": "Carter" }
];
alert(employees[0].lastName); // mode 1
alert(employees[0]["lastName"]); // mode 2