使用 PowerShell 循环确定对象和/或 JSON 值的深度



我正在使用api来收集特定票证的评论列表,票证有嵌套的评论,这些评论从api返回,如下所示:

{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
]
}

对于任何父注释,子注释的个数可以是n。我最终试图获得文本值为每个"评论"标记,直到"注释"为止。标签为空

我想做一个父对象,然后尝试追加属性搜索,直到它返回null。

$n = 1
$exists = $true
while ($exists){ 

$string = ".comments"     
$search = $string * $n
$search = $search.Substring(1)
$m = $i.$search
$commentVal = $m.comments
$textValue = $m.text
$textValue
if ($textValue -ne ''){
$comments +=  $textValue
}

if ($commentVal){            
$exists = $true
}else{           
$exists = $false
}
$n++    
} 

这确实有效,但只适用于一次迭代。例如,如果$search = "comments.comments"我美元。$search不起作用,但是$search = "comments";我美元。

将响应转换为对象并在comments属性上递归的解决方案:

$rawJson = @'
{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
]
}
'@
$jsonObj = $rawJson | ConvertFrom-Json
$comment = $jsonObj.Comments
$allComments = while ($null -ne $comment) {
$comment.text
$comment = $comment.Comments
}

编辑
(稍微解释一下可能会有帮助)

如果$search = "comments.comments"不起作用,$i.$search不起作用,但$search = "comments"不起作用;$i.$search可以工作

这是预期的,如果不是直观的。$i.comments告诉PowerShell索引注释属性,$i.comments.comments告诉它做两次。

问题是当使用像$search = "comments.comments"这样的变量时,$search没有展开;PowerShell将查找文字属性comments.comments

在这个json上试试你的代码:

{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
],
"comments.comments": [
{
"text": "test 2.0",
"comments": [
{
"text": "i'm not empty"
}
]
}
],
"comments.comments.comments": [
{
"text": "test 3.0",
"comments": [
{
"text": "i'm not empty"
}
]
}
]
}

最新更新