首页 > 解决方案 > 我可以根据输入中的嵌套属性输出带有 jq 的属性吗?

问题描述

这是从使用 jq 从嵌套 JSON 对象中提取选定属性的后续步骤,这使那里的 OP 从嵌套对象中摆脱了大量不需要的属性。

我遇到了同样的问题,但不是一个以 [ 开头的数组,而是一个 JSON 对象流,每个对象都像这样:

{
   "localHostName" : "rest-2-17ve6",
   "port" : "80",
   "requestHeaders" : {
      "x-forwarded-port" : "443",
      "x-forwarded-host" : "dummy.com",
      "content-length" : "15959431",
      "accept" : "*/*",
      "x-forwarded-for" : "10.1.9.11",
      "authorization" : "hash is present",
      "expect" : "100-continue",
      "forwarded" : "for=10.5.9.1;host=dummy.com;proto=https",
      "content-type" : "application/json",
      "host" : "dummy.com",
      "x-forwarded-proto" : "https",
      "user-agent" : "curl/7.51.0"
   },
   "uri" : "/2/data/saveList",
   "protocol" : "HTTP/1.1",
   "threadName" : "http-nio-8080-exec-10",
   "requestBytes" : 15959431,
   "applicationDuration" : 44135,
   "responseStatus" : "200",
   "remoteIpAddress" : "10.1.10.1",
   "responseHeaders" : {
      "X-XSS-Protection" : "1; mode=block",
      "Content-Type" : "application/json;charset=UTF-8",
      "X-Content-Type-Options" : "nosniff",
      "Cache-Control" : "no-cache, no-store, max-age=0, must-revalidate",
      "Date" : "Wed, 20 Jun 2018 15:53:27 GMT",
      "Transfer-Encoding" : "chunked",
      "Vary" : "Accept-Encoding",
      "X-Frame-Options" : "DENY",
      "Expires" : "0",
      "Pragma" : "no-cache"
   },
   "isoDateTime" : "2018-06-20T15:52:42.466913985Z",
   "method" : "POST",
   "username" : "rd7y1",
   "localIpAddress" : "10.129.9.238",
   "responseBytes" : 2,
   "requestContentExcerpt" : "blah",
   "totalDuration" : 44869,
   "responseContentExcerpt" : " [] "
}

我想在命令行上过滤流,所以我只得到:

{ 
   "isoDateTime" : "2018-06-20T15:52:42.466913985Z",
   "method" : "POST",
   "username" : "rd7y1",
   "requestHeaders.user-agent" : "Rcurl"
}

我试过cat /logs/json.log | jq -cC 'map(requestHeaders|={user-agent})'了,但出现语法错误。

标签: jsonsyntaxnestedkeyjq

解决方案


  1. 由于 jq 是面向流的,因此您只需使用select(...)而不是map(select(...))

  2. 看起来您打算.requestHeaders."user-agent"在选择标准中使用。

  3. 通常建议尽可能避免使用cat

  4. 根据您声明的要求,您应该删除 -c 命令行选项。

  5. 由于“Rcurl”没有出现在您的示例输入中,我将使用确实出现的字符串。

所以在你的情况下,你最终会得到类似的东西:

< /logs/json.log jq '
  select(.requestHeaders."user-agent" == "curl/7.51.0")
  | {isoDateTime, method, username,
     "requestHeaders.user-agent": .requestHeaders."user-agent"}'

推荐阅读