我是jq的新手,在解析JSON时遇到问题 我有这样的JSON
{
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "Found On:"
},
{
"type": "text",
"text": "Name of component"
}
]
},
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "The Problem:"
},
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "Description of the problem"
}
]
}
]
}
]
}
我想要获取所有“文本”属性的值。但是,可以看出此JSON是多层嵌套结构。 那我怎么能实现我的 预期结果:
Found On:
Name of component
The Problem:
Description of the problem
答案 0 :(得分:1)
man jq
:
..
无需参数即可进行递归的快捷方式。它旨在类似于XPath
//
运算符。请注意,..a
无法正常工作;请改用..|a
。在下面的示例中,我们使用..|.a?
在.
之下的任何对象中找到对象键“ a”的所有值。jq '..|.a?' [[{"a":1}]] => 1
您需要做的就是稍微调整一下上面的示例以抑制null
:
$ jq '..|(.text?)//empty' file
Found On:
Name of component
The Problem:
Description of the problem
答案 1 :(得分:0)
您可能想考虑一种替代解决方案-使用针对JSON的步行路径unix工具: jtc
,您的查询将类似于:
bash $ <file.json jtc -w'<text>l:'
"Found On:"
"Name of component"
"The Problem:"
"Description of the problem"
bash $
在jtc
中的搜索词素<..>
是递归的,后缀l
指示(递归)搜索以匹配标签(而不是数据),而量词:
指示查找所有实例。
如果您想删除引号,请将-qq
添加到cli。
PS>披露:我是jtc
工具的创建者