JQ:用另一个文件中的对应值替换键 [英] JQ: Replace keys with corresponding value in another file
问题描述
我试图用另一个文档中相应的键将对象的值替换为原始JSON中的键的值.
I'm trying to replace the value of a key in my original JSON with the value of an object with the corresponding key in another document.
这是我的两个文件:文件1:
These are my two files: File 1:
{
"-KaM0otlgWxXniYiacFe": {
"-LNxx1IiX6oYTxJ4IXx2": true
},
"-KlJTvbfonIMI_-YfS5R": {
"-LNxx1IbaB-yrZ623hrX": true
}
}
文件2:
{
"-KaM0otlgWxXniYiacFe": {
"a": "-L-b__nH9PlMcz0stDDE",
"b": "-L7ZNKSZy570TlrQUzHM",
"c": "-Kaae3MsQUyViCKPs8Iv"
},
"-KlJTvbfonIMI_-YfS5R": {
"a": "-LAlXKfUUTdYDeCZH-u-",
"b": "-L7ZNKSTnob7w0HXjHr6",
" c": "-KYYicPD7VA9DEF_rus3"
}
}
目标是创建3个新文件,其中每个文件中的原始键已替换为a,b和c的值.
The goal is to create 3 new files, where the original keys have been replaced with the value of a, b and c in each file.
查看"a"时所需的结果:
Desired result when looking against "a":
{
"-L-b__nH9PlMcz0stDDE": {
"-LNxx1IiX6oYTxJ4IXx2": true
},
"-LAlXKfUUTdYDeCZH-u-": {
"-LNxx1IbaB-yrZ623hrX": true
}
}
我尝试使用以下方式:
cat file1.json | jq --slurpfile file2 file2.json '| map(with_entries(.key = .file2[.key].a'
但是我以前没有使用过jq,所以感觉很笨.
But I'm feeling rather clueless as I havn't used jq before.
感谢您的帮助.
更新:
如果文件1中的密钥可能不存在于文件2中,导致出现无法将null(空)用作对象密钥"),我该如何处理?
How do I handle the scenario where the key from File 1 might not exist in File 2, resulting in the "Cannot use null (null) as object key"?
推荐答案
不是jq的专家,但这是我想出的:
Not an expert on jq, but here is what I've come up with:
jq --arg k a --argfile file2 file2.json 'with_entries(.key |= $file2[.][$k])' file1.json > out_a.json
为其他键和输出文件更改-arg k
和 out_a.json
.
Change --arg k a
and out_a.json
for other keys and output files.
这篇关于JQ:用另一个文件中的对应值替换键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!