7

PowerShell ConvertTo-Json 複雜巢狀結構注意事項

 2 years ago
source link: https://blog.darkthread.net/blog/converto-json-depth/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
PowerShell ConvertTo-Json 複雜巢狀結構注意事項-黑暗執行緒

ConvertTo-Json/ConvertFrom-Json 是少數我用不順手的 PowerShell 指令,過去就踩過幾次雷(ConvertFrom-JSON 解析大型 JSON 報錯ConvertFrom-Json 還原陣列無法 Where-Object 篩選),最近又踩到一枚。

例如以下這段程式,JSON 用 ConvertFrom-Json 轉成物件再 ConvertTo-Json 回 JSON 會走味,O 屬性物件的 SA 陣列會變成字串:

$json = @"
[
    { "A": [1,2], "O": { "SA": [100] } },
    { "A": [3,4], "O": { "SA": ["One","Two"] } }
]
"@
$a = $json | ConvertFrom-Json
$a | ConvertTo-Json

原因很簡單,我不夠認真,使用前沒詳閱公開說明書 - ConvertTo-Json 遇到屬性型別是物件(非 string、int 之類單純型別),該物件屬性型別又是物件的巢狀結構式,預設只處理到第二層,再往下會直接轉成字串。用下面這個例子可以看得更清楚:

$complexObj = @{
    Lv = 1
    Lv1Obj = @{
        Lv = 2
        Lv2Obj = @{
            Lv = 3
            Lv3Obj = @{
                Lv = 4
            }
        }
    }
}
$complexObj | ConvertTo-Json

轉出來的 JSON,Lv3Obj 被轉成字串 - System.Collections.Hashtable,而在文章開始的案例 "100" 跟 "One Two" 也是 PowerShell 將 @(100)、@("One","Two") 轉成字串的結果。

ConvertTo-Json 提供了一個 -Depth n 參數可指定要深入到第幾層,以上案例加 -Depth 3 就是我們預期的結果了。

沒什麼大學問,要嘛花點時間把唐詩三百首官方文件從頭唸到尾,要嘛踩個一次雷馬上就能學會,或者也可以訂閱本部落格,英雄自然你來當,踩雷,我來! XD

and has 0 comments

Comments

Be the first to post a comment

Post a comment

Comment
Name Captcha 10 - 9 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK