2016-06-27 38 views
9

說我有輸入:JQ:JSON的輸出對象數組

{ 
    "name": "John", 
    "email": "[email protected]" 
} 
{ 
    "name": "Brad", 
    "email": "[email protected]" 
} 

如何獲取輸出:

[ 
    { 
     "name": "John", 
     "email": "[email protected]" 
    }, 
    { 
     "name": "Brad", 
     "email": "[email protected]" 
    } 
] 

我都嘗試:

jq '[. | {name, email}]' 

jq '. | [{name, email}]' 

這既給我的輸出

[ 
    { 
     "name": "John", 
     "email": "[email protected]" 
    } 
] 
[ 
    { 
     "name": "Brad", 
     "email": "[email protected]" 
    } 
] 

我還沒有看到選項在本細則的陣列輸出,任何幫助讚賞

+0

如何給新數組命名而不是匿名數組?所以{「people」:[{「name」:「Brad」,「email」:「[email protected]」}]} – archcutbank

+0

@ user372429您只需將{people:}包裹在輸出內容中,像這樣:jq -s'{people:。 }'

回答

10

使用啜食模式:

o --slurp/-s: 

     Instead of running the filter for each JSON object 
     in the input, read the entire input stream into a large 
     array and run the filter just once. 
$ jq -s '.' < tmp.json 
[ 
    { 
    "name": "John", 
    "email": "[email protected]" 
    }, 
    { 
    "name": "Brad", 
    "email": "[email protected]" 
    } 
] 
+0

完美,謝謝!當時間到了時會接受 –