gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:12:17 25 4
gpt4 key购买 nike

我正在使用 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"$i.$search 不起作用,但 $search = "comments"; $i.$search 确实有效。

最佳答案

这是您的解决方案,可将响应转换为对象并在 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
}

编辑
(一些解释可能会有所帮助)

if $search = "comments.comments" $i.$search does not work, but $search = "comments"; $i.$search does work.


这是意料之中的,如果不是直观的。 $i.comments告诉 PowerShell 在 comments 属性上建立索引,然后 $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"
}
]
}
]
}

关于json - 使用 PowerShell 循环确定对象和/或 JSON 值的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65894693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com