2015-02-11 108 views
4

我已經能夠得到這個。如何使用jq過濾json對象的數組?

JSON輸入, 'data.json':

[ 
    { 
    "Selected": null, 
    "Family Name": "Jones", 
    "Couple Name": "Jones, Adam & Rachael Margaret", 
    "Family Phone": "404-4477", 
    "Family Email": "[email protected]", 
    "Family Address": "777 Aggies Court Kindly, California 95388 ", 
    "Head Of House Name": "Jones, Adam", 
    "Head Of House Phone": "(583) 404-2488", 
    "Head Of House Email": "[email protected]", 
    "Spouse Name": "Jones, Rachael Margaret", 
    "Spouse Phone": null, 
    "Spouse Email": null, 
    "Child Name": null, 
    "Child Phone": null, 
    "Child Email": null 
    }, 
    { 
    "Selected": "x", 
    "Family Name": "Xiong", 
    "Couple Name": "Xiong, Arlene Frances", 
    "Family Phone": null, 
    "Family Email": null, 
    "Family Address": "888 Walnut Ave. Blatant, California 95388 ", 
    "Head Of House Name": "Xiong, Arlene Frances", 
    "Head Of House Phone": "583-500-7917", 
    "Head Of House Email": "[email protected]", 
    "Spouse Name": null, 
    "Spouse Phone": null, 
    "Spouse Email": null, 
    "Child Name": null, 
    "Child Phone": null, 
    "Child Email": null 
    }, 
    { 
    "Selected": "x", 
    "Family Name": "Blair", 
    "Couple Name": "Blair, Toby & Silvia", 
    "Family Phone": "358-4645", 
    "Family Email": null, 
    "Family Address": "333 Cindy St. Stoic, California 95388 ", 
    "Head Of House Name": "Blair, Toby", 
    "Head Of House Phone": null, 
    "Head Of House Email": "[email protected]", 
    "Spouse Name": "Blair, Silvia", 
    "Spouse Phone": null, 
    "Spouse Email": null, 
    "Child Name": null, 
    "Child Phone": null, 
    "Child Email": null 
    } 
] 

我可以使用該過濾:

cat data.json | jq '.[] | select(.Selected != null) | {"Head Of House Name", "Head Of House Phone", "Head Of House Email", "Family Phone", "Family Email"}' 

結果:

{ 
    "Head Of House Name": "Xiong, Arlene Frances", 
    "Head Of House Phone": "583-500-7917", 
    "Head Of House Email": "[email protected]", 
    "Family Phone": null, 
    "Family Email": null 
} 
{ 
    "Head Of House Name": "Blair, Toby", 
    "Head Of House Phone": null, 
    "Head Of House Email": "[email protected]", 
    "Family Phone": "358-4645", 
    "Family Email": null 
} 

通知沒有陣列括號在對象數組周圍,對象之間沒有逗號......表示結果不是數組。

問題是,結果不是一個對象數組(坦白說,我不知道它是什麼)。我如何從一個json對象數組開始,過濾它們並最終得到一個過濾的對象列表?

回答

10

當您使用過濾器.[]時,實際上是將數組結果分解爲每個項目的單獨結果。你最終看到的是每個單獨的結果,一個接一個。

,以確保它們保存爲一個數組,你可以把結果返回到一個數組用方括號包裹你的過濾器:

[ 
    .[] | 
    select(.Selected != null) | 
    { 
     "Head Of House Name", 
     "Head Of House Phone", 
     "Head Of House Email", 
     "Family Phone", 
     "Family Email" 
    } 
] 

或使用map()過濾器把它作爲一個數組,你然後可以刪除.[]部分:

map(
    select(.Selected != null) | 
    { 
     "Head Of House Name", 
     "Head Of House Phone", 
     "Head Of House Email", 
     "Family Phone", 
     "Family Email" 
    } 
) 

如果你問我,你應該堅持map()