我正在使用jq解析日志数据,偶尔日志中包含格式错误的内容(无效的json),当这种情况发生时,jq会在此时放弃处理。
有没有一种方法可以让jq在通过stderr报告问题的同时继续处理可能的问题?
我知道,如果JSON中包含换行符,则jq如果从下一行开始可能会遇到麻烦,但是在这种情况下,您最终还是会发现合法的JSON消息的开头并可以继续处理。
使用jq-1.5,我可以执行以下操作:
# Include All Errors in output as a string
cat example.log | jq -R '. as $raw | try fromjson catch $raw'
# Skip all errors and keep going
cat example.log | jq -R 'fromjson?'
Run Code Online (Sandbox Code Playgroud)
非json的行将作为字符串输出,其他所有内容均为json
如果你有 jq 1.5,答案是:yes,但一般来说,预处理(例如使用 hjson 或 any-json)会更可取。
无论如何,这个想法只是为了利用 try/catch 功能。这是使用inputs过滤器的插图。请注意,通常应使用 -n 选项调用 jq 以使其工作。
def handle: inputs | [., "length is \(length)"] ;
def process: try handle catch ("Failed", process) ;
process
Run Code Online (Sandbox Code Playgroud)
[1,2,3]
{id=546456, userId=345345}
[4,5,6]
Run Code Online (Sandbox Code Playgroud)
$ jq -n -f recover.jq bad.json
[
"[1,2,3]",
"length is 3"
]
"Failed"
[
"[4,5,6]",
"length is 3"
]
Run Code Online (Sandbox Code Playgroud)