解析 JSON 并篡改其对象值

解析 JSON 并篡改其对象值

我有一个名为 xyz.json 的 json 文件,如下所示

[
    {
        "annotations": [ "a" , "b" , "c" ],
        "class": "image",
        "filename": "vc00_02201.png"
    },
    {
        "annotations": [],
        "class": "image",
        "filename": "vc00_02202.png"
    }
    {
        "annotations": [],
        "class": "image",
        "filename": "vc00_02203.png"
    },
    {
        "annotations": [],
        "class": "image",
        "filename": "vc00_02204.png"
    }
]

我需要使用 shell 脚本将对象“annotations”从“filename”:“vc00_02201.png”复制到同一 xyz.json 文件中“filename”的“annotations”:“vc00_02204.png”。预期输出:

[
    {
        "annotations": [ "a" , "b" , "c" ],
        "class": "image",
        "filename": "vc00_02201.png"
    },
    {
        "annotations": [],
        "class": "image",
        "filename": "vc00_02202.png"
    }
    {
        "annotations": [],
        "class": "image",
        "filename": "vc00_02203.png"
    },
    {
        "annotations": [ "a" , "b" , "c" ],
        "class": "image",
        "filename": "vc00_02204.png"
    }
]

答案1

$cat xyz.json | jq '.[3].annotations=.[0].annotations'

答案2

这也可以通过以下方式实现jtc一行:

bash $ cat xyz.json | jtc -w'<vc00_02204.png>[-1][annotations]' -eu jtc -w'<vc00_02201.png>[-1][annotations]' xyz.json \; 
[
   {
      "annotations": [
         "a",
         "b",
         "c"
      ],
      "class": "image",
      "filename": "vc00_02201.png"
   },
   {
      "annotations": [],
      "class": "image",
      "filename": "vc00_02202.png"
   },
   {
      "annotations": [],
      "class": "image",
      "filename": "vc00_02203.png"
   },
   {
      "annotations": [
         "a",
         "b",
         "c"
      ],
      "class": "image",
      "filename": "vc00_02204.png"
   }
]
bash $ 

当然,它可以通过引用数组的直接成员来完成,例如:

bash $ cat xyz.json | jtc -w'[3][annotations]' -eu jtc -w'[0][annotations]' xyz.json \;

但这样通过文件名交叉引用的整个点就没有实际意义了。

相关内容