我需要使用 ps 从 JSON 文件中提取一些信息。JSON 具有嵌套components
数组,其中也可以包含components
数组。
{
"name": "app",
"components": [
{
"component_name": "comp1",
"component_packages": [
"comp1_package1",
"comp1_package2"
],
"project_id": "1234",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": [
{
"component_name": "comp1.1",
"component_packages": [
"comp1.1_package1"
],
"project_id": "2345",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": [
{
"component_name": "comp1.1.1",
"component_packages": [
"comp1.1.1_package1"
],
"project_id": "3456",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": []
}]
},
{
"component_name": "comp1.2",
"component_packages": [
"comp1.2_package1"
],
"project_id": "4567",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": []
}
]
},
{
"component_name": "comp2",
"component_packages": [
"comp2_package1",
"comp2_package2"
],
"project_id": "5678",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": [
{
"component_name": "comp2.1",
"component_packages": [
"comp2.1_package1"
],
"project_id": "6789",
"file_path": "requirements_file",
"ref": "%%VERSION%%",
"components": []
}
]
}
]
}
对于每个component
内部,components
我需要执行一个脚本来收集更多信息,但我很难一一迭代所有元素。
我开始将 JSON 转换为 psobject ( Get-Content -Raw "$json_path" | ConvertFrom-Json
)
我不想修复 JSON 的深度。所以脚本应该具有适应性。
我尝试使用while
循环
$comp = $object.components
while ( $comp -ne "" ) {
$comp | ForEach-Object {
# to something
}
}
但这样它不适合,因为即使我覆盖$comp
,脚本也会忘记一些条目。