这是我的Data.json。它有多级数组。我必须获得所有数组元素:
{
"host": "http://localhost:5000",
"dlls": [
{
"files": [
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
}
]
},
{
"json": [
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
}
]
}
]
}
在我目前的PS脚本中,我只能迭代一个级别:
$json = $null;
$jsonparsed = $null;
$validJson = $false;
try {
$json = Get-Content -Raw $file;
$jsonparsed = ConvertFrom-Json $json -ErrorAction Stop;
$validJson = $true;
} catch {
$validJson = $false;
}
if ($validJson) {
Write-Host "Provided text has been correctly parsed to JSON";
Write-Host $jsonparsed;
} else {
Write-Host "Provided text is not a valid JSON string" -ForegroundColor "Red";
return;
}
我必须解析所有JSON数组元素。检索每个“路径”和“存储”的值。请告诉我如何在PowerShell版本5中执行此操作。我通过加载第三方程序集找到了解决方案。但是我不允许使用任何外部组件。没有外部装配,它是否可以解析?
答案 0 :(得分:1)
如果将其粘贴到PowerShell(v5)窗口中:
$jsonparsed = convertFrom-Json @'
{
"host": "http://localhost:5000",
"dlls": [
{
"files": [
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
},
{
"path": ".\\Xml.dll",
"store": ".\\DX\\OpenXml.dll"
}
]
},
{
"json": [
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
},
{
"path": ".\\index.json",
"store": ".\\DX\\index.json"
}
]
}
]
}
'@
Write-Host $jsonparsed.host
ForEach ($dll in $jsonparsed.dlls) {
ForEach ($file in $dll.files) {
Write-Host $file.path
Write-Host $file.store
}
ForEach ($json in $dll.json) {
Write-Host $json.path
Write-Host $json.store
}
}
你应该得到这个:
.\Xml.dll
.\DX\OpenXml.dll
.\Xml.dll
.\DX\OpenXml.dll
.\Xml.dll
.\DX\OpenXml.dll
.\Xml.dll
.\DX\OpenXml.dll
.\Xml.dll
.\DX\OpenXml.dll
.\index.json
.\DX\index.json
.\index.json
.\DX\index.json
.\index.json
.\DX\index.json
.\index.json
.\DX\index.json
.\index.json
.\DX\index.json
.\index.json
.\DX\index.json