json - 将 JSON 对象传递给 jq 参数

标签 json bash parameter-passing jq data-processing

数据示例 - sample.json(完整示例:https://pastebin.com/KFkVmc2M)

    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}

我希望使用 jq 的脚本可以工作,但尚未找到其他解决方案。

   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'

我希望但没有得到的最​​终结果:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

现在它只是将对象作为字符串返回,我已经尝试了很多不同的方法来解决这个问题。我对使用 JSON 和 jq 还很陌生,但根据我目前所读的内容,解决方案可能不像我希望的那么简单?

简单地说,为什么对象没有作为 sample.json 对象的值返回,我必须做什么才能让它工作?

谢谢!

致:切普纳

{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}

最佳答案

这是使用@CharlesDuffy 建议的方法的变体解决方案:

$ config='{"Host": ["http", "host"], 
           "Vulnerability": ["opts", "vulns", 0], 
           "ISP": ["isp"]}'
$ jq --argjson config "$config" '
   . as $in
   | $config
   | map_values( . as $p | $in | getpath($p) )' pastebin.json

输出:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

这顺便强调了@chepner 的观点:$config 所需的维护和维护不亚于相应的 jq 查询所需的维护和维护,而 jq 查询语言——在设计上——提供了更多的灵 active 。

关于json - 将 JSON 对象传递给 jq 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47276532/

相关文章:

python - 如何使用 Python 中的 requests 模块获取大尺寸 JSON 文件

linux - 使用java启动远程进程

string - 使用 Unicode Delphi 调用 DLL 时出错

python - 修改json文件

javascript - 返回一个表示图像为 JSON 的 byte[]?

bash - 在 sed 中扩展变量

ruby-on-rails - Rails 在参数中为 M 到 M 关联形成传递数组

ios - 将数据从 TableViewController 传递到 TableViewCell

php - JSON:从另一个域检索 JSON 文件

c++ - 在 C 中运行没有系统调用的 sed