英文:
jq - how to transform a nested structure into another?
问题
I can help you with the translation. Here's your content translated to Chinese:
我有大约950个JSON文件需要转换,但我有点卡住了。我已经编写了一个Shell脚本来遍历文件,删除一些键,但我在如何转换它方面卡住了。这是我的原始文件:
{
"name": "Ted Mosby",
"addresses": {
"data": [
{
"key": "address key",
"value": "any xpto"
}
]
}
}
我需要将data
转换为另一种格式,输出必须是:
{
"name": "Ted Mosby",
"addresses": {
"data": [{
"value": "any xpto",
"remoteRef": {
"key": "address key",
"courrierStrategy": "Auto"
}
}]
}
}
有没有办法使用jq来实现这个?我正试图避免编写Python来执行它。
英文:
I have a like 950 json files that I need to transform but I'm kinda stuck. I have right a shell script to iterate over files, delete somekeys but I got stuck on how transform it. Here I have my original file:
{
"name": "Ted Mosby",
"addresses": {
"data": [
{
"key": "address key",
"value": "any xpto"
}
]
}
}
I need to transform data
into another format and output must be:
{
"name": "Ted Mosby",
"addresses": {
"data": [{
"value": "any xpto",
"remoteRef": {
"key": "address key",
"courrierStrategy": "Auto"
}
}]
}
}
Is there any way to achieve it using jq? I am trying to avoid write a python to perform it.
答案1
得分: 2
你可以通过对原始项目的每个元素应用转换来更新.data
数组,使用原始项目中的.key
和.value
:
{
"name": "Ted Mosby",
"addresses": {
"data": [
{
"value": "any xpto",
"remoteRef": {
"key": "address key",
"courrierStrategy": "Auto"
}
}
]
}
}
英文:
You could update |=
the .data
array by applying a transformation to each of its elements, using the .key
and .value
from the original item:
.addresses.data |= map({value, remoteRef: {key, courrierStrategy: "Auto"}})
{
"name": "Ted Mosby",
"addresses": {
"data": [
{
"value": "any xpto",
"remoteRef": {
"key": "address key",
"courrierStrategy": "Auto"
}
}
]
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论