2015-11-09 99 views
3

我試圖修改嚴重格式化JSON文本文件的數組,目前看起來是這樣的:PowerShell的:格式化JSON嵌套數組到對象

[ 
    ["val1", "val2", "val3", "val4"], 
    ["val5", "val6", "val7", "val8"], 
    ["val9", "val10", "val11", "val12"] 
] 

,我有包含其他數組字段名稱

["title1", "title2", "title3", "title4"] 

我想輸出final.json文本文件看起來像這樣:

[ 
    {"title1": "val1", "title2": "val2", "title3": "val3", "title4": "val4"}, 
    {"title1": "val5", "title2": "val6", "title3": "val7", "title4": "val8"}, 
    {"title1": "val9", "title2": "val10", "title3": "val11", "title4": "val12"} 
] 

我想在b EST的辦法是採取每行,通過,分割,然後將它們添加到一起的foreach-ING在冠軍的名字,但我不如何做到這一點在PowerShell中十分肯定。

回答

2

既然你與結構化數據處理在這裏,我想最好的辦法是解析JSON,並將得到的對象。創建你想要的對象,然後再轉換回JSON:

$j1 = @' 
[ 
    ["val1", "val2", "val3", "val4"], 
    ["val5", "val6", "val7", "val8"], 
    ["val9", "val10", "val11", "val12"] 
] 
'@ 

$j2 = @' 
["title1", "title2", "title3", "title4"] 
'@ 

$a1 = $j1 | ConvertFrom-Json 
$a2 = $j2 | ConvertFrom-Json 

0..($a1.Count-1) | ForEach-Object { 
    $i = $_ 
    $props = @{} 
    0..($a2.Count-1) | ForEach-Object { 
     $props[$a2[$_]] = $a1[$i][$_] 
    } 
    New-Object PSOBject -Property $props 
} | ConvertTo-Json 

ConvertTo-JsonConvertFrom-Json你需要序列化/反序列化JSON的的cmdlet。然後你只需要處理這些對象。

在這種情況下,我會通過每個頂層數組中$a1並創建包含所需的屬性哈希表。然後我創建一個帶有這些屬性的PSObject。 ,但未通過ForEach-Object小命令(結果是那些對象的數組)然後把它直接管道輸送到ConvertTo-Json,得到了所需要的輸出返回。

2

我認爲一個較好的方法是在通過ConvertFrom JSON的第一JSON格式來讀取,則取陣列的該陣列和對於每一行,創建從一個散列表例如PSCustomObject [PSCustomObject]@{title1=$arr[$row][0]; title2=$arr[$row][1];...}。一旦你有了這個PSCustomObject數組,將它轉換回帶有ConvertTo-Json的JSON。