jq:将数组转换为按文件名索引的对象? [英] jq: convert array to object indexed by filename?

查看:103
本文介绍了jq:将数组转换为按文件名索引的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jq 如何将数组转换为按文件名索引的对象,或者读取多个文件进入一个按文件名索引的对象?

Using jq how can I convert an array into object indexed by filename, or read multiple files into one object indexed by their filename?

例如

jq -s 'map(select(.roles[]? | contains ("mysql")))' -C dir/file1.json dir/file2.json

这给了我想要的数据,但是我需要知道它们来自哪个文件.

This gives me the data I want, but I need to know which file they came from.

所以不是

[
    { "roles": ["mysql"] },
    { "roles": ["mysql", "php"] }
]

对于输出,我想要:

{
    "file1": { "roles": ["mysql"] },
    "file2": { "roles": ["mysql", "php"] }
}

如果可能,我确实希望将".json"文件扩展名也剥离掉, ,而只是除去基名(不包括dir).

I do want the ".json" file extension stripped too if possible, and just the basename (dir excluded).

{ "roles": ["mysql"] }

file2.json

file2.json

{ "roles": ["mysql", "php"] }

file3.json

file3.json

{ }

我的真实文件中显然还包含其他内容,但这对于本示例来说已经足够了. file3只是为了证明有时会丢失角色".

My real files obviously have other stuff in them too, but that should be enough for this example. file3 is simply to demonstrate "roles" is sometimes missing.

换句话说:我试图在其角色"列表中查找包含"mysql"的文件.我需要将文件名和内容组合到一个JSON对象中.

In other words: I'm trying to find files that contain "mysql" in their list of "roles". I need the filename and contents combined into one JSON object.

为进一步简化问题,

jq 'input_filename' f1 f2

为我提供所有想要的文件名,但是我不知道如何将它们组合成一个对象或数组.

Gives me all the filenames like I want, but I don't know how to combine them into one object or array.

鉴于,

jq -s 'map(input_filename)' f1 f2

给我相同的文件名,每个文件重复一次.例如[ "f1", "f1" ]代替[ "f1", "f2" ]

Gives me the same filename repeated once for each file. e.g. [ "f1", "f1" ] instead of [ "f1", "f2" ]

推荐答案

如果您的jq具有inputs(jq 1.5也是如此),则只需调用一次jq即可完成任务. 另外,使用any可能比遍历.roles的所有元素更有效.

If your jq has inputs (as does jq 1.5) then the task can be accomplished with just one invocation of jq. Also, it might be more efficient to use any than iterating over all the elements of .roles.

技巧是使用-n选项调用jq,例如

The trick is to invoke jq with the -n option, e.g.

jq -n '
  [inputs
   | select(.roles and any(.roles[]; contains("mysql")))
   | {(input_filename | gsub(".*/|\\.json$";"")): .}]
  | add' file*.json

这篇关于jq:将数组转换为按文件名索引的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆