2017-07-28 45 views
0

我希望能夠使用jq在輸入JSON中輸出2個數組的'產品'...例如,給定下列輸入JSON:如何使用jq生成輸入中存在的兩個數組的笛卡爾乘積JSON

{ 
    "quantities": [ 
     { 
      "product": "A", 
      "quantity": 30 
     }, 
     { 
      "product": "B", 
      "quantity": 10 
     } 
     ], 
    "portions": [ 
     { 
      "customer": "C1", 
      "percentage": .6 
     }, 
     { 
      "customer": "C2", 
      "percentage": .4 
     } 
    ] 
} 

我想產生以下輸出(或類似...):

[ 
    { 
    "customer": "C1", 
    "quantities": [ 
     { 
      "product": "A", 
      "quantity": 18 
     }, 
     { 
      "product": "B", 
      "quantity": 6 
     } 
     ] 
    }, 
    { 
    "customer": "C2", 
    "quantities": [ 
     { 
      "product": "A", 
      "quantity": 12 
     }, 
     { 
      "product": "B", 
      "quantity": 4 
     } 
     ] 
    } 
] 

因此,換句話說,對於每一部分,使用它的百分比的值並將其應用於每個產品數量。鑑於2只及2部應該產生4個結果..給3只及2部應該產生6個結果,等...

我使用foreach過濾器已經做了一些嘗試,但都無濟於事......

回答

0

我認爲這會做你想做的。

[ 
    .quantities as $q 
| .portions[] 
| .percentage as $p 
| { 
    customer, 
    quantities: [ 
     $q[] | .quantity = .quantity * $p 
    ] 
    } 
] 
0

既然你表明你想要的笛卡爾乘積,而你只給了樣本輸出指示,你在找什麼,它可能是值得一提的是一個能獲得笛卡爾積得很乾脆:

.portions[] + .quantities[] 

這產生的物體,如:

{ 
    "product": "B", 
    "quantity": 10, 
    "customer": "C2", 
    "percentage": 0.4 
} 

你可以然後使用reduce或(效率更低,group_by)至以任何你真正想要的形式獲取數據。

例如,假定。客戶永遠是一個字符串,我們可以改變 輸入到請求的格式如下:

def add_by(f;g): reduce .[] as $x ({}; .[$x|f] += [$x|g]); 

[.quantities[] + .portions[]] 
| map({customer, quantities: {product, quantity: (.quantity * .percentage)}}) 
| add_by(.customer; .quantities) 
| to_entries 
| map({customer: .key, quantities: .value })