Reputation: 181
I am using an api to gather a list of comments for particular tickets, the tickets have nested comments which are returned from the api like so:
{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
]
}
The number of child comments can be n for any parent comment. I'm ultimately trying to get the text value for each "comments" tag until the "comments" tag is null.
I thought about making a parent object then trying to append the property search until it returns 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++
}
This does work but only for one iteration. i.e. if $search = "comments.comments" $i.$search does not work, but $search = "comments"; $i.$search does work.
Upvotes: 2
Views: 1219
Reputation: 10019
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"
}
]
}
]
}
Upvotes: 2