Home > Web Front-end > JS Tutorial > js解析json数据的几种方法

js解析json数据的几种方法

WBOY
Release: 2016-06-01 09:54:58
Original
7269 people have browsed it

第一种方法:使用eval解析
如果服务器返回的是json字符串,那么首先要将json字符串转化为javascript对象。可以通过javascript的eval函数进行转化:代码如下:
第一个实例: 

<code><script type="text/javascript">
var jsonString='{"name":"wxp","age":30,"friends":[{"name":"liu","age":29},{"name":"qiu","age":28}]}'; 
jsonObj=eval("("+jsonString+")");
for(var i in jsonObj){
    if(typeof jsonObj[i]!='object'){
        alert(jsonObj[i]);
    }else{
        for(var sub in jsonObj[i]){
            for(var subo in  jsonObj[i][sub]){
                alert(jsonObj[i][sub][subo]);
            }
        }
    }
}
</script></code>
Copy after login


第二个实例:

<code><script type="text/javascript">
var jsonObj=[
    {
        name:"wxp",
        age:30
    },
    {
        name:"zhangsan",
        age:22
    },
    {
        name:"lisi",
        age:26
    },
    {
        name:"wang",
        age:23
    }
]

for(var i in jsonObj){
    for(var j in jsonObj[i]){
        alert(j+":"+jsonObj[i][j]);
    }
}
</script></code>
Copy after login

 


第二种方法:使用Funtion函数。代码如下:

 

<code><script type="text/javascript">
var jsonStr='[{"name":"wxp","age":30},{"name":"zhangsan","age":22},{"name":"lisi","age":26},{"name":"wang","age":23}]';
var obj = new Function("return" + jsonStr)()
for(var i in obj){
    for(var j in obj[i]){
        alert(j+":"+obj[i][j]);
    }
}
</script></code>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template