2016-06-14 64 views
0

我想通過終端使用終端命令或腳本編輯json的結構。 如果我有這樣一個JSON文件結構:通過命令行向JSON添加一個父屬性

 { 
     "Helloo": [ 
     { 

      "AlbumTitle": { 
      "S": "Famous" 
      }, 
      "SongTitle": { 
      "S": "Call Me Today" 
      }, 
      "Artist": { 
      "S": "No One You Know" 
      } 

     }, 
{ 

      "AlbumTitle": { 
      "S": "Famous1" 
      }, 
      "SongTitle": { 
      "S": "Call Me Today1" 
      }, 
      "Artist": { 
      "S": "No One You Know11" 
      } 

     } 
     ], 
     "Music": [ 
     { 

      "Album": { 
      "S": "Pop Songs" 
      }, 
      "Production": { 
      "S": "X-series" 
      }, 
      "Song": { 
      "S": "Once upon 
      }, 
      "Artist": { 
      "S": "XYZ" 
      } 

     } 
     ] 
    } 

所以在這裏,我想加上「Putrequest」和「項目」屬性的陣列的每一個項目。所以我想輸出是這樣的:

{ 
     "Helloo": [ 
     { 
     PutRequest":{ 
      "Item":{ 

      "AlbumTitle": { 
      "S": "Famous" 
      }, 
      "SongTitle": { 
      "S": "Call Me Today" 
      }, 
      "Artist": { 
      "S": "No One You Know" 
      } 

     } 
     } 
     }, 
{ 
PutRequest":{ 
      "Item":{ 

      "AlbumTitle": { 
      "S": "Famous1" 
      }, 
      "SongTitle": { 
      "S": "Call Me Today1" 
      }, 
      "Artist": { 
      "S": "No One You Know11" 
      } 

     } 
     } 
     } 
     ], 
     "Music": [ 
     { 
PutRequest":{ 
      "Item":{ 
      "Album": { 
      "S": "Pop Songs" 
      }, 
      "Production": { 
      "S": "X-series" 
      }, 
      "Song": { 
      "S": "Once upon 
      }, 
      "Artist": { 
      "S": "XYZ" 
      } 
} 
} 
     } 
     ] 
    } 

我試圖使用Jq這個,但仍然掙扎..請幫助我使用命令提示符或bash/shell腳本將這些屬性添加到json。 感謝

+1

請告訴我們你已經嘗試過jq。 – cb0

+0

你知道這不是正確的JSON嗎? ''S「:」從前'< - 缺少報價'「' – andlrc

回答

1

假設你實際上得到有效的JSON以下JQ表達可能爲你工作:

map_values(map({"PutRequest": { "Item": .}})) 

用法:

jq 'map_values(map({"PutRequest": { "Item": .}}))' file.json 

擊穿:

map_values(   # Map values iterate over an object and assign the 
         # returned value to the property 
    map(    # Map iterate over an array and assign the returned value 
         # to the index, and creates a new array if an object is 
         # mapped 
    {     # Return an object 
     "PutRequest": { # With PutRequest as a property 
     "Item": .  # And Item, which contains the value (.) 
     } 
    } 
) 
) 
+0

@andlrs:謝謝你soo ..你解決了我的問題.. – Tedd

+0

@andlrs:再次感謝你..我接受了你的回答:) – Tedd

+0

@Tedd我很高興我可以幫你,現在你應該閱讀兩遍,並自己重寫:-) – andlrc