[英]jq - parsing& replacement based on key-value pairs within json
I have a json file in the form of a key-value map. 我有一个键-值映射形式的json文件。 For example:
例如:
{
"users":[
{
"key1":"user1",
"key2":"user2"
}
]
}
I have another json file. 我还有另一个json文件。 The values in the second file has to be replaced based on the keys in first file.
必须根据第一个文件中的键替换第二个文件中的值。
For example 2nd file is: 例如,第二个文件是:
{
"info":
{
"users":["key1","key2","key3","key4"]
}
}
This second file should be replaced with 第二个文件应替换为
{
"info":
{
"users":["user1","user2","key3","key4"]
}
}
Because the value of key1 in first file is user1. 因为第一个文件中的key1的值为user1。 this could be done with any python program, but I am learning jq and would like to try if it is possible with jq itself.
这可以用任何python程序完成,但是我正在学习jq,并想尝试一下jq本身是否可行。 I tried different combinations with reading file using slurpfile, then select & walk etc. But couldn't arrive at the required solution.
我尝试了使用slurpfile读取文件的不同组合,然后选择&walk等。但是无法达到所需的解决方案。
Any suggestions for the same will be appreciated. 任何建议相同的将不胜感激。
jq
solution: jq
解决方案:
jq --slurpfile users 1st.json '$users[0].users[0] as $users
| .info.users |= map(if in($users) then $users[.] else . end)' 2nd.json
The output: 输出:
{
"info": {
"users": [
"user1",
"user2",
"key3",
"key4"
]
}
}
Since .users[0] is a JSON dictionary, it would make sense to use it as such (eg for efficiency): 由于.users [0]是JSON字典,因此按原样使用它(例如,为了提高效率)将是有意义的:
Invocation: jq -c --slurpfile users users.json -f program.jq input.json 调用:jq -c --slurpfile users users.json -f program.jq input.json
program.jq: program.jq:
$users[0].users[0] as $dict
| .info.users |= map($dict[.] // .)
Output: 输出:
{"info":{"users":["user1","user2","key3","key4"]}}
Note: the above assumes that the dictionary contains no null or false values, or rather that any such values in the dictionary should be ignored. 注意:以上假设字典中不包含任何null或false值,或者应忽略字典中的任何此类值。 This avoids the double lookup that would otherwise be required.
这避免了原本需要的双重查找。 If this assumption is invalid, then a solution using
has
or in
(eg as provided by RomanPerekhrest) would be appropriate. 如果该假设无效,则使用
has
或in
的解决方案(例如,由RomanPerekhrest提供)将是适当的。
(See "comments".) (看评论”。)
$users[0].users[0] as $dict
| second
| .info.users |= (map($dict[.] | select(. != null)))
It is highly inadvisable to use redirection to overwrite an input file. 强烈建议不要使用重定向来覆盖输入文件。 If you have or can install
sponge
, then it would be far better to use it. 如果您有或可以安装
sponge
,那么使用它会更好。 For further details, see eg "What is jq's equivalent of sed -i?" 有关更多详细信息,请参见例如“ jq等同于sed -i?” in the jq FAQ .
在jq FAQ中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.