首页 > 解决方案 > jq 替换文件中的数组键值

问题描述

我有一个包含这些数据的 json 文件:

{
  "data": [                                                                                                                                      
    {
      "name": "table",    
      "values": [    
        "This is old data",    
        "that needs to be",    
        "replaced."    
      ]    
    }    
  ]    
}    

但我在这里的挑战是我需要用文本或 csv 文件中的单词替换该值数组:

this
this
this
is
is
an
an
array

我的输出需要有(尽管我可能会在一行中使用所有这些词......):

      "values": [
        "this this this",
        "is is",
        "an an",
        "array"    
      ],

这可能只用jq吗?还是我必须让 awk 帮忙?我已经开始了 awk 之路:

awk -F, 'BEGIN{ORS=" "; {print "["}} {print $2} END{{print "]"}}' filename

但我知道这里还有一些工作......

然后我遇到了jq -Rn inputs。但我还没有弄清楚如何或是否可以获得所需的结果。

感谢您的任何指示。

标签: jsonjq

解决方案


假设您有一个名为的原始 ASCII 文本文件file和一个输入 JSON 文件,您可以这样做

jq --rawfile txt file '.data[].values |= ( $txt | split("\n")[:-1] | group_by(.) | map(join(" ")) )' json

生产

{
  "data": [
    {
      "name": "table",
      "values": [
        "an an",
        "array",
        "is is",
        "this this this"
      ]
    }
  ]
}

推荐阅读