


Detailed explanation of JavaScript conversion and parsing JSON method examples_javascript skills
The examples in this article describe JavaScript conversion and parsing JSON methods. Share it with everyone for your reference, the details are as follows:
The json format data is as follows:
var json = { 'jquery': [{ "id": "1", "type": "ASP.NET", "title": "JSON全解析"}] } alert(json.jquery[0].id); alert(json.jquery[0].type); alert(json.jquery[0].title);
Javascript parses json data:
window.onload = function() { var json = { "China": "[{'City':'上海','value':'1'},{'City':'南京','value':'2'},{'City':'杭州','value':'3'},{'City':'武汉','value':'4'}]" } var datas = eval(json.China); for (var i = 0; i < datas.length; i++) { alert(datas[i].City); alert(datas[i].value); } }
Supplement: jQuery parsing json method:
Use the eval function to parse and jquery’s each method to traverse
Use JQuery to parse JSON data. As the transmission object of JQuery asynchronous request, the result returned after JQuery request is a json object. What is considered here is the form of string returned by the server in JSON form. For encapsulation using plug-ins such as JSONObject The JSON object is similar to this and will not be explained here.
The JSON string set is first given here. The string set is as follows:
var data=" { root: [ {name:'1',value:'0'}, {name:'6101',value:'北京市'}, {name:'6102',value:'天津市'}, {name:'6103',value:'上海市'}, {name:'6104',value:'重庆市'}, ] }";
Based on the data types obtained asynchronously by JQuery - json objects and strings, here we introduce the results processing methods obtained by the two methods.
eval()
For the JSON string returned by the server, if the jquery asynchronous request does not specify the type, or accepts it in string mode, then it needs to be objectified. It is not too troublesome, or it is to put the string in eval() Executed once. This method is also suitable for obtaining json objects using ordinary javascipt. The following is an example:
// 转换为json对象 var dataObj=eval("("+data+")");
Why do we need to add ("(" data ")"); to eval here?
The reason is: the problem of eval itself. Since json starts and ends with "{}", it will be processed as a statement block in JS, so it must be forced to be converted into an expression.
The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object instead of executing it as a statement when processing JavaScript code. For example, take the object literal {}. If no outer brackets are added, then eval will recognize the braces as the beginning and end marks of the JavaScript code block, and {} will be considered to execute an empty statement. So the following two execution results are different:
// return undefined alert(eval("{}"); // return object[Object] alert(eval("({})");
This kind of writing can be seen everywhere in JS. For example: (function()) {}(); When doing closure operations, etc.
//输出root的子对象数量 alert(dataObj.root.length); $.each(dataObj.root,fucntion(idx,item){ if(idx==0){ return true; } //输出每个root子对象的名称和值 alert("name:"+item.name+",value:"+item.value); })
For general js to generate json objects, you only need to replace the $.each() method with a for statement, and the others remain unchanged.
JSON string returned by the server
For the JSON string returned by the server, if the jquery asynchronous request sets the type (usually this configuration attribute) to "json", or uses the $.getJSON() method to obtain the server return, then the eval() method is not needed Because the result obtained at this time is already a json object, you only need to call the object directly. Here, the $.getJSON method is used as an example to illustrate the data processing method:
$.getJSON("http://www.xxxx.com/",{param:"gaoyusi"},function(data){ //此处返回的data已经是json对象 //以下其他操作同第一种情况 $.each(data.root,function(idx,item){ if(idx==0){ //同countinue,返回false同break return true; } alert("name:"+item.name+",value:"+item.value); }); });
What needs special attention here is that the eval() method in method 1 dynamically executes the string (possibly a js script), which can easily cause system security issues. Therefore, you can use some third-party client script libraries that circumvent eval(). For example, JSON in JavaScript provides a script library of no more than 3k.
The second method of parsing is to use Function objects. Its typical application is the parsing of returned data such as success under the AJAX method in JQuery.
var json='{"name":"CJ","age":18}'; data =(new Function("","return "+json))();
The data at this time is a json object that will be parsed.
I hope this article will be helpful to everyone in JavaScript programming.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

How to convert full-width English letters into half-width letters In daily life and work, sometimes we encounter situations where we need to convert full-width English letters into half-width letters, such as when entering computer passwords, editing documents, or designing layouts. Full-width English letters and numbers refer to characters with the same width as Chinese characters, while half-width English letters refer to characters with a narrower width. In actual operation, we need to master some simple methods to convert full-width English letters into half-width letters so that we can process text and numbers more conveniently. 1. Full-width English letters and half-width English letters

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code
