ConvertTo-JSON 错误解析数组
ConvertTo-JSON falsely parses arrays
这里也回答了这个问题:
GitHub:ConvertFrom-Json 和 ConvertTo-Json 破坏数组
Mircrosoft Docs: ConvertTo-JSON
TL;DR
如果你用 ConvertTo-JSON
保存你的 .json 并且它破坏了它,你可能想要指定 -Depth
参数,因为它的默认值为 2 并且它不会解析嵌套超出此范围的对象。
原文Post:
所以我想加载,然后通过 PowerShell 脚本从 JSON 文件中保存数据。 JSON 在对象中包含一个数组,如下所示:
{
"head": {
"head2": {
"data0": "a",
"data1": "b"
},
"head3": {
"data8": [
"x",
"y",
"z"
],
"data9": "hello"
}
}
}
注意数组“data8”。
现在,当我像这样加载和保存文件时:Get-Content test.json | ConvertFrom-JSON | ConvertTo-JSON
我想以完全相同的文件结束,因为我没有更改任何内容。然而结果是这样的:
{
"head": {
"head2": {
"data0": "a",
"data1": "b"
},
"head3": {
"data8": "x y z",
"data9": "hello"
}
}
}
“data8”已缩减为单个字符串,我很难找出原因。它似乎发生在 ConvertTo-JSON
期间,因为当我还没有这样做时,它会给我一个包含 x、y 和 z 的字符串数组。
例如(Get-Content test.json | ConvertFrom-JSON).head.head3.data8
将导致
x
y
z
和(Get-Content test.json | ConvertFrom-JSON).head.head3.data8 -is [array]
给出True
我尝试过的事情:(get-content test.json | convertfrom-json).head.head3.data8
test.json 中的各种编码方法,但即使我将文件另存为 utf8 并将 -encoding utf8
添加到 Get-Content
时也会发生这种情况,所以我不认为这是必须做的
为了尝试,我什至在 ConvertTo-JSON
中添加了 -compress
,但也无济于事。
好吧,显然只有 PowerShell parses data up to a depth of 2 by default. So as pointed out Here 你必须用 ConvertTo-Json
的 depth
参数指定深度
这里也回答了这个问题:
GitHub:ConvertFrom-Json 和 ConvertTo-Json 破坏数组
Mircrosoft Docs: ConvertTo-JSON
TL;DR
如果你用 ConvertTo-JSON
保存你的 .json 并且它破坏了它,你可能想要指定 -Depth
参数,因为它的默认值为 2 并且它不会解析嵌套超出此范围的对象。
原文Post:
所以我想加载,然后通过 PowerShell 脚本从 JSON 文件中保存数据。 JSON 在对象中包含一个数组,如下所示:
{
"head": {
"head2": {
"data0": "a",
"data1": "b"
},
"head3": {
"data8": [
"x",
"y",
"z"
],
"data9": "hello"
}
}
}
注意数组“data8”。
现在,当我像这样加载和保存文件时:Get-Content test.json | ConvertFrom-JSON | ConvertTo-JSON
我想以完全相同的文件结束,因为我没有更改任何内容。然而结果是这样的:
{
"head": {
"head2": {
"data0": "a",
"data1": "b"
},
"head3": {
"data8": "x y z",
"data9": "hello"
}
}
}
“data8”已缩减为单个字符串,我很难找出原因。它似乎发生在 ConvertTo-JSON
期间,因为当我还没有这样做时,它会给我一个包含 x、y 和 z 的字符串数组。
例如(Get-Content test.json | ConvertFrom-JSON).head.head3.data8
将导致
x
y
z
和(Get-Content test.json | ConvertFrom-JSON).head.head3.data8 -is [array]
给出True
我尝试过的事情:(get-content test.json | convertfrom-json).head.head3.data8
test.json 中的各种编码方法,但即使我将文件另存为 utf8 并将 -encoding utf8
添加到 Get-Content
时也会发生这种情况,所以我不认为这是必须做的
为了尝试,我什至在 ConvertTo-JSON
中添加了 -compress
,但也无济于事。
好吧,显然只有 PowerShell parses data up to a depth of 2 by default. So as pointed out Here 你必须用 ConvertTo-Json
depth
参数指定深度