Today, I encountered a problem of converting the JSON object format to a JS array, and I found that I was doing some work on JSON. A small code is written here to be used by people in need.
To get straight to the point, first declare a JSON object array, in this case, JS array using "[]" differentiated, and the object is from "{}" distinction, of course, these problems you must be very familiar with the great God.
var data=[{"url": "Http://www.baidu.com", "Oldname": "Baidu"},{"url": "http://www.sina.com.cn/", "oldname": "Sina"}];
This is a typical array of JSON objects. Personally think this format in the program is very convenient, but still some people like to use array, here does not explore this situation, and not to JSON and pure JS arrays do too much evaluation.
With a lot of data, there's no direct built-in good function to convert JSON data into objects, but we can assign it to a two-dimensional array of JS by looping through the JSON object data, and it is worth declaring that JS has no two-dimensional array of strict meaning, and it needs to be declared again before it can be used, Otherwise, the browser will complain.
function Json_array (data) {
var len=eval (data). length;
var arr=[];
for (Var i=0;i<len;i++) {
arr[i] =[]; the two-dimensional array in//js must be declared repeatedly, otherwise undefind
arr[i][' url ']=data[i].url;
arr[i][' oldname ']=data[i].oldname;
}
return arr;
}
Json_array (data);
This approach allows you to iterate through the JSON array, but only if you know the format of your JSON object and the data structure you need.
Eval () converts the JSON string into a JSON data format. But this is not necessary, as the example above, but the above example is quite simple, if data is a JSON string, using "{}" start and end, then in JS, "{}" in the content, will be treated as a block of code that must be forced into a block of code using eval, and the specific use of eval can be viewed in the manual.