如何使用groovy在json中选择少数元素

时间:2016-05-27 12:03:30

标签: json groovy

我有以下json文件,

{
    "catalog": {
        "book": [
            {
                "id": "bk101",
                "author": "Gambardella, Matthew",
                "title": "XML Developer's Guide",
                "genre": "Computer",
                "price": "44.95",
                "publish_date": "2000-10-01",
                "description": "An in-depth look at creating applications with XML."
            },
            {
                "-id": "bk102",
                "author": "Ralls, Kim",
                "title": "Midnight Rain",
                "genre": "Fantasy",
                "price": "5.95",
                "publish_date": "2000-12-16",
                "description": "A former architect battles "
            }
        ]
    }
}

我想从上面得到的内容很少,例如。

catalog.book[0].title应该给出结果

{
    "catalog": {
        "book": [
            { "title": "XML Developer's Guide"}
        ]
    }
}

但它只会给结果{"title": "XML Developer's Guide"},缺少树。

请帮忙。

1 个答案:

答案 0 :(得分:0)

    you have to create a  function which return the  subset of json .subset contain all the field you want
    //simple javascript code 

    function subset_of_json(jsonobj,fieldsYouWant){
        //fieldsYouWant is an array ['title'] or ['title' ,'id'] or any field you want
        var json ={catalog :{book:[]}};
        var bookArr =jsonobj.catalog.book; 
        for(var i=0;i<bookArr.length;i++){
              var obj ={};
              for(var k=0;k<fieldsYouWant.length;k++){
                  obj[fieldsYouWant[k]]=bookArr[i][fieldsYouWant[k]];
               }
              json.catalog.book.push(obj)

       }
    return json 

    }