想使用Powershell将json输出转换为数组或列表。
我尝试使用ConvertFrom-Json
转换输出,然后获取键名称和值。需要建议。
json输出:
{
"demo1": {
"type": [
"tuple",
[
[
"list",
"string"
],
[
"list",
"string"
]
]
],
"value": [
[
"123"
],
[
"456"
]
]
},
"demo2": {
"type": [
"tuple",
[
"string",
"string"
]
],
"value": [
"abc",
"xyz"
]
}
}
使用Powershell要将其转换如下:
demo1 = [["123"],["456"]]
demo2 = ["abc","xyz"]
谢谢。
答案 0 :(得分:1)
似乎很简单地使用convertfrom-json:
$a = get-content file.json | convertfrom-json
$a.demo1.value
123
456
$a.demo2.value
abc
xyz
您想要将其作为json吗?
$a.demo1.value | ConvertTo-Json -Compress
[["123"],["456"]]
$a.demo2.value | ConvertTo-Json -Compress
["abc","xyz"]
答案 1 :(得分:1)
应该是这样的:
$t = '{
"demo1": {
"type": [
"tuple",
[
[
"list",
"string"
],
[
"list",
"string"
]
]
],
"value": [
[
"123"
],
[
"456"
]
]
},
"demo2": {
"type": [
"tuple",
[
"string",
"string"
]
],
"value": [
"abc",
"xyz"
]
}
}'
$t = ConvertFrom-Json $t
$t | Get-Member | Where-Object {$_.MemberType -eq 'NoteProperty'} | foreach {
$element = $_.Name
echo 'Property Name: '
echo $element
echo 'Elements: '
echo ($t.$element.value | ConvertTo-Json -Depth 99)
}
在这一点上,powershell核心的行为似乎与v3-5略有不同,因此,尽管powershell核心将直接为您提供正确的结果,但是较旧的版本此时需要进行一些额外的处理,请参见此处:Why does powershell give different result in one-liner than two-liner when converting JSON?