我想处理这个数据
{
"results": [
{
"headword": "binding",
"senses": [
{
"definition": [
"a promise, agreement etc that must be obeyed"
]
}
]
},
{
"headword": "non-binding",
"senses": [
{
"definition": [
"a non-binding agreement or decision does not have to be obeyed"
],
"examples": [
{
"text": "The industry has signed a non-binding agreement to reduce pollution."
}
]
}
]
}
]
}
进入这个
{
"headword": "binding",
"definition": "a promise, agreement etc that must be obeyed",
"examples": null
}
{
"headword": "non-binding",
"definition": "a non-binding agreement or decision does not have to be obeyed",
"examples": "The industry has signed a non-binding agreement to reduce pollution."
}
该命令
cat data.json | jq '.results[] | {headword: .headword, definition: .senses[].definition[], examples: .senses[].examples[].text}'
错误为"无法在null上迭代">
为了克服这一点,此命令使用"。[]?'过滤
cat data.json | jq '.results[] | {headword: .headword, definition: .senses[].definition[], examples: .senses[].examples[]?.text}'
但这只输出
{
"headword": "non-binding",
"definition": "a non-binding agreement or decision does not have to be obeyed",
"examples": "The industry has signed a non-binding agreement to reduce pollution."
}
那么,如何迭代null而不跳过数组呢?
使用if/else语句可能会有所帮助。
jq '.results[] | {
headword,
definition: .senses[0].definition[0],
examples: (if .senses[0].examples then .senses[0].examples[0].text else null end)
}' data.json
正如@oguzismail含蓄地指出的,假设senses数组只有一个元素是有风险的,尤其是从名字的选择来看人们预计,每个词条都可能有不止一种意义。可以对.个例子进行类似的观察,但是如果examples有多个元素,Q并没有明确说明应该做什么。
因此,在下文中,我将选择一种安全的方法,因为它可以容易地调节以满足更具体的要求。
.results[]
| { headword }
+ (.senses[]
| { definition: .definition[0],
examples: (if has("examples")
then [.examples[].text]
else null end) } )