2017-07-11 29 views
3

我有一個特定的json內容,我需要獲取包含字符/的值的所有鍵。需要從包含特定字符的JSON獲取所有鍵值對'/'

JSON

{ "dig": "sha256:d2aae00e4bc6424d8a6ae7639d41cfff8c5aa56fc6f573e64552a62f35b6293e", 
"name": "example", 
"binding": { 
    "wf.example.input1": "/path/to/file1", 
    "wf.example.input2": "hello", 
    "wf.example.input3": 
    ["/path/to/file3", 
     "/path/to/file4"], 
    "wf.example.input4": 44 
    } 
} 

我知道我能得到所有含有文件路徑或使用查詢jq 'paths(type == "string" and contains("/"))'文件路徑陣列的關鍵。這會給我等的輸出:

[ "binding", "wf.example.input1" ] 
[ "binding", "wf.example.input3", 0] 
[ "binding", "wf.example.input3", 1 ] 

現在,我都包含一些文件路徑作爲其數值的元素,是有辦法來獲取key和值相同,然後將它們保存爲另一種JSON?例如,在爲這個問題提到的JSON中,我需要將輸出作爲另一個包含所有匹配路徑的JSON。我的輸出JSON應該如下所示。

{ "binding": 
    { "wf.example.input1": "/path/to/file1", 
    "wf.example.input3": [ "/path/to/file3", "/path/to/file4" ] 
    } 
} 

回答

2

以下JQ濾波器將產生所需的輸出,如果給定的輸入,這是非常相似的實例中,但它遠遠健壯和掩蓋了一些細節是從問題描述不清楚。然而,應該很容易修改,根據過濾器具有更精確規格:

. as $in 
| reduce paths(type == "string" and test("/")) as $path ({}; 
    ($in|getpath($path)) as $x 
    | if ($path[-1]|type) == "string" 
     then .[$path[-1]] = $x 
     else .[$path[-2]|tostring] += [$x] 
     end) 
| {binding: .} 

輸出:

{ 
    "binding": { 
    "wf.example.input1": "/path/to/file1", 
    "wf.example.input3": [ 
     "/path/to/file3", 
     "/path/to/file4" 
    ] 
    } 
} 
+0

這工作絕對沒問題。 – Shashank

+0

你能解釋一下這個命令到底在做什麼嗎? – Shashank

相關問題