输入json:
[
{
"Authors": "Author1, Author2, Author3",
"Affiliation": "Here, There, Everywhere"
},
{
"Authors": "Author4, Author5",
"Affiliation": "Nirvana, Utopia"
}
]
期望的输出:
{
"authors": [
{
"Name": "Author1",
"Affiliation": "Here"
},
{
"Name": "Author2",
"Affiliation": "There"
},
{
"Name": "Author3",
"Affiliation": "Everywhere"
}
]
},
{
"authors": [
{
"Name": "Author4",
"Affiliation": "Nirvana"
},
{
"Name": "Author5",
"Affiliation": "Utopia"
}
]
}
我可以用以下内容读取两个数组的第一个元素:
jq '.[] as $o | $o.Authors | split(", ") as $authors | $o.Affiliation | split(", ") as $affiliation | { "Authors": [ { "Name": $authors[.0], "Affiliation": $affiliation[.0]} ] }'
但是我很难理解如何让jq迭代整个(任意长度)字符串以产生完整的所需输出。
答案 0 :(得分:2)
jq
解决方案:
jq '[.[] | [(.Authors | split(", ")), (.Affiliation | split(", "))]
| transpose | { authors: map({ Name:.[0], Affiliation:.[1] }) }]' input.json
输出:
[
{
"authors": [
{
"Name": "Author1",
"Affiliation": "Here"
},
{
"Name": "Author2",
"Affiliation": "There"
},
{
"Name": "Author3",
"Affiliation": "Everywhere"
}
]
},
{
"authors": [
{
"Name": "Author4",
"Affiliation": "Nirvana"
},
{
"Name": "Author5",
"Affiliation": "Utopia"
}
]
}
]