2017-09-14 12 views
1

我有一個配置,其內容要與來自單獨文件的片段交換。我將如何整齊地實現這一目標?將JSON哈希中的數組元素替換爲來自其他文件的內容

配置文件可能看起來像:

# config file 
{ 
    "keep": "whatever type of value", 
    "manipulate": [ 
     { 
      "foo": "bar", 
      "cat": { 
       "color": "grey" 
      }, 
      "type": "keep", 
      "detail": "keep whole array element" 
     }, 
     { 
      "stuff": "obsolete", 
      "more_stuff": "obsolete", 
      "type": "replace", 
      "detail": "replace whole array element with content from separate file" 
     }, 
     { 
      "foz": "baz", 
      "dog": { 
       "color": "brown" 
      }, 
      "type": "keep", 
      "detail": "keep whole array element" 
     }, 

    ], 
    "also_keep": "whatever type of value" 
} 

含量(即將從單獨的文件)插入作爲替代過時數組元素的:

# replacement 
{ 
    "stuff": "i want that", 
    "fancy": "very", 
    "type": "new" 
} 

期望的結果應該看起來像:

# result 
{ 
    "keep": "whatever kind of value", 
    "manipulate": [ 
     { 
      "foo": "bar", 
      "cat": { 
       "color": "grey" 
      }, 
      "type": "keep", 
      "detail": "keep whole array element" 
     }, 
     { 
      "stuff": "i want that", 
      "fancy": "very", 
      "type": "new" 
     }, 
     { 
      "foz": "baz", 
      "dog": { 
       "color": "brown" 
      }, 
      "type": "keep", 
      "detail": "keep whole array element" 
     }, 

    ], 
    "also_keep": "whatever kind of value", 
} 

要求:

  • 內容更換需要根據type鍵的值來完成。
  • 最好使用jq和常用的bash/linux工具。
  • 數組元素順序應該保持相同
+0

你需要解釋這種更換是如何工作的,因爲這不是明顯對我來說,你是如何得到「結果」,從「配置文件」。這不是簡單的替換。 – Stalinko

+0

@Stalinko你可能錯過了第二節_#replacement_?而且,是的,問題是,如何通過使用片段_#replacement_ – ITL

回答

1

JQ解決方案:

jq --slurpfile repl repl.json '.manipulate=[.manipulate[] 
    | if .type=="replace" then .=$repl[0] else . end]' config.json 
  • repl.json - JSON文件,其中包含更換JSON數據

  • --slurpfile repl repl.json - 讀取所有的JSON文本在指定的文件中並綁定解析的JSON v的數組alues給定的全局變量

輸出:

{ 
    "keep": "whatever type of value", 
    "manipulate": [ 
    { 
     "foo": "bar", 
     "cat": { 
     "color": "grey" 
     }, 
     "type": "keep", 
     "detail": "keep whole array element" 
    }, 
    { 
     "stuff": "i want that", 
     "fancy": "very", 
     "type": "new" 
    }, 
    { 
     "foz": "baz", 
     "dog": { 
     "color": "brown" 
     }, 
     "type": "keep", 
     "detail": "keep whole array element" 
    } 
    ], 
    "also_keep": "whatever type of value" 
} 
+0

Thx從原始輸入(_#configfile_)獲取(_#result_)Thx,您爲我創造了一天..完美地工作 – ITL

+0

@ITL,不客氣 – RomanPerekhrest

1
jq --slurpfile repl repl.json '.manipulate |= 
    map(if .type=="replace" then $repl[0] else . end)' config.json 
相關問題