Here's a solution for you that converts the response to an object and recurses on the comments
property:
$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
}
Edit
(a bit of explanation might be helpful)
if $search = "comments.comments"
$i.$search
does not work, but $search = "comments"
; $i.$search
does work.
This is expected, if not intuitive. $i.comments
tells PowerShell to index on the comments property, and $i.comments.comments
tells it to do twice.
Problem is when using a variable like in the case $search = "comments.comments"
, $search
is not expanded; PowerShell will look for the literal property comments.comments
.
Try your code on this 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"
}
]
}
]
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…