开发者社区 问答 正文

如何获取json对象中的特定值?

{
    "id": "some",
    "title": "some",
    "author": {
        "name": "\u95eb\u9759"
    },
    "link": [{
        "@attributes": {
            "href": "http://localhost/",
            "rel": "some"
        }
    },
    {
        "@attributes": {
            "href": "http://localhost/",
            "rel": "some"
        }
    },
    {
        "@attributes": {
            "href": "http://localhost/",
            "rel": "some"
        }
    }]
}

如上,对于服务器返回的json数据,如何获取Link中第一个@attributes的href值?

展开
收起
a123456678 2016-03-10 16:54:49 2767 分享 版权
1 条回答
写回答
取消 提交回答
  • function getJsonValue(obj,name){
            var result = null;
            var value  = null;
            for(var key in obj){        
                value = obj[key];
                if(key == name){
                return value;
            } else {
                if( typeof value == "object" ){
                result = getJsonValue(value,name);
                }
            }
        }
        return result;
    }

    采用递归方式来查找josn中的你需要的key.

    但是还不支持 数组,你可以自己扩充,思路就是这样!

    全选复制放进笔记var taskId = getJsonValue(jsonobj,"history");
    console.log(taskId);
    var jsonobj = { "semantic":{"taskId":"8.4.3"},"history":"cn.xxxx.fund"};

    2019-07-17 18:57:56
    赞同 展开评论
问答分类:
问答地址: