2017-03-08 56 views
0

所有鍵和值,並分別存儲在一個數組我有一個JSON文件是這樣的:如何使用shell腳本解析器JQ

{ 
"images1" : 
    { 
     "size" : "29x29", 
     "idiom" : "iphone", 
     "filename" : "[email protected]", 
     "scale" : "2x" 
    }, 
"images2" : 
    { 
     "size" : "29x30", 
     "idiom" : "iphone2", 
     "filename" : "[email protected]", 
     "scale" : "22x" 
    } 
} 

我將通過JSON對象名稱作爲輸入。因此,如果我知道「images1」是對象,那麼我需要將該對象的所有鍵和值存儲在兩個單獨的數組中,以便我可以在進一步處理中使用它們。

任何幫助,非常感謝。 感謝

回答

1

您可以使用以下方法:。

jq ".$1 | { keys: keys_unsorted, values: [.[]] }" 

其中$1應提供要解決項目的名稱(注意,這假設你在腳本中使用這個你可能會想用fedorqui的替代品)。

它將產生一個對象,其屬性keys將是$1values相關值的數組中的鍵的陣列:

$ echo '{ 
"images1" : 
    { 
     "size" : "29x29", 
     "idiom" : "iphone", 
     "filename" : "[email protected]", 
     "scale" : "2x" 
    }, 
"images2" : 
    { 
     "size" : "29x30", 
     "idiom" : "iphone2", 
     "filename" : "[email protected]", 
     "scale" : "22x" 
    } 
}' | jq ".images1 | { keys: keys_unsorted, values: [.[]] }" 
{ 
    "keys": [ 
    "size", 
    "idiom", 
    "filename", 
    "scale" 
    ], 
    "values": [ 
    "29x29", 
    "iphone", 
    "[email protected]", 
    "2x" 
    ] 
} 
+0

獎勵Aaron..Your解決方案適用於me..Thanks很多 –