json - 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
。但我还没有弄清楚如何或是否可以获得所需的结果。
感谢您的任何指示。
解决方案
假设您有一个名为的原始 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"
]
}
]
}
推荐阅读
- java - 如何在 JTable 中显示 Oracle 表列表?
- python-3.x - 有没有办法在非交互模式下使用 azure artifacts-keyring 身份验证?我想在 azure func 中安装私有 py 包(工件)
- flutter - Flutter:如何在 WebView 和 InteractiveViewer 之间分派手势?
- java - Firebase:数据未以正确格式存储
- c# - 用户购买产品时如何更新最新数量?数据库没有减少数量
- google-colaboratory - 当我保持 n_jobs=8 时,google colab 分配了多少个“CPU”内核,有什么方法可以检查吗?
- python - 将 dask 任务流导出到 svg
- javascript - 通过 Ajax 和 PHP 下载 CSV 内容
- wordpress - 如何在 WordPress 中向 Facebook Pixel 事件添加事件 ID?
- java - 我可以将子类传递给需要超类的方法,并使用新的属性值吗?