如何将嵌套结构转换为另一种形式?

huangapple go评论64阅读模式
英文:

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"
        }
      }
    ]
  }
}

Demo

huangapple
  • 本文由 发表于 2023年6月8日 02:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定