Use JSON data and javascriptjson data in JavaScript
JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.
JSON syntax
JSON is constructed in two structures:
Object-a set of name/value pairs. In different languages, it is understood as an object, record, structure, Dictionary, hash table, keyed list, or associated array. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs.
Array -- ordered list of values. In most languages, it is understood as an array. An array starts with "[" (left square brackets) and ends with "]" (right square brackets. Values are separated by commas.
JSON has no variables or other control structures. JSON is only used for data transmission.
Assign JSON data to a variable
For example, you can create a new JavaScript variable and assign a value to the JSON-format data string:
var people ={ "programmers": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }],"authors": [{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }],"musicians": [{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }]}
This is very simple; now people contains the data in JSON format as shown above. However, this is not enough, because the data access method does not seem obvious.
Access Data
Although it does not seem obvious, the long string above is actually an array. After you put this array into the JavaScript variable, you can easily access it. In fact, you only need to use the dot notation to represent array elements. Therefore, to access the first project name in the programmers list, you only need to use the following code in JavaScript:
people.programmers[0].lastName;
Note that the array index starts from scratch. Therefore, this line of code first accesses the data in the people variable, then moves to the entry called programmers, and then to the first record ([0]). Finally, it accesses the value of the lastName key. The result is the string value "McLaughlin ".
The following are examples of using the same variable.
people.authors[1].genre // Value is "fantasy"people.musicians[3].lastName // Undefined. This refers to the fourth entry,and there isn't onepeople.programmers[2].firstName // Value is "Elliotte"
With this syntax, You can process data in any JSON format without using any additional JavaScript toolkit or API.
Modify JSON data
Just as you can access data with periods and parentheses, you can easily modify the data in the same way:
people.musicians[1].lastName = "Rachmaninov";
After converting a string to a JavaScript json object, you can modify the data in the variable as follows.
Note: The objects in json format are different from those in json text.
Var obj = {name: "Zhang San", "sex": 'mal'}; // json format object var str = "{name:" Zhang San "," sex ": 'male'} "; // json string (json text)
Convert back to string
Of course, if you cannot easily convert an object back to the text format mentioned in this article, all data modifications are of little value. In JavaScript, this conversion is also very simple:
var newJSONtext = people.toJSONString();
That's all! Now you can obtain a text string that can be used anywhere. For example, you can use it as a request string in an Ajax application.
More importantly, any JavaScript Object can be converted to JSON text. It is not only applicable to variables that are originally assigned values using JSON strings. To convert an object named myObject, you only need to execute the same command:
<script type="text/javascript">function Car(make,model,year,color){this.make=make; this.model=model; this.year=year; this.color=color;} function showCar(){var carr = new Car("Dodge","Coronet R/T",1968,"yellow"); alert(carr.toJSONString()); }</script>
This is the biggest difference between JSON and other data formats. If JSON is used, you only need to call a simple function to obtain formatted data and use it directly. For other data formats, the conversion between the original data and the formatted data is required. Even if you use an API like Document Object Model (which provides a function to convert your data structure to text), you also need to learn this API and use the Object of the API, instead of using native JavaScript objects and syntaxes.
The final conclusion is that if you want to process a large number of JavaScript objects, JSON is almost certainly a good choice, in this way, you can easily convert data to the format (Ajax) that can be sent to the server-side program in the request ).
How to convert a JSON string to a JSON object
To use str1 above, you must use the following method to first convert it to a JSON object:
// Convert the JSON string to the JSON object var obj = eval ('+ str + ')');
Or
Var obj = str. parseJSON (); // converts a JSON string to a JSON object.
Or
Var obj = JSON. parse (str); // converts a JSON string to a JSON object.
Then, you can read:
Alert(obj.name);Alert(obj.sex);
NOTE: If obj is a JSON object, it is still a JSON object after eval () function conversion (even Multiple conversions), but parseJSON () is used () A problem occurs after the function is processed (a syntax exception is thrown ).
Articles you may be interested in:
- Js parses json instances using eval and shares precautions
- Examples of using the default format and json format for java object serialization and deserialization
- Jquery serialized form json data returned after ajax submission
- Be careful when using double quotation marks in JSON
- How to Use PHP to output Chinese JSON strings
- Introduction to JSON. parse () and JSON. stringify ()
- Directly create JSON data in JS and traverse and use
- How to define a literal object using json data format in PHP
- An error occurs when JSON. parse is used to convert a json string to a json object.
- Generate and use Json data instances in Android
- PHP does not escape Chinese characters when using the json_encode Function
- In ASP. NET, MVC calls the JsonResult method using AJAX and returns a custom error message.