从 JSON 中查找 key 的值 [英] Find the value of key from JSON

查看:23
本文介绍了从 JSON 中查找 key 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从这一行 JSON 中提取 "id" 键.

I'd like to extract the "id" key from this single line of JSON.

我相信这可以用 grep 来完成,但我不确定正确的方法.

I believe this can be accomplished with grep, but I am not sure on the correct way.

如果有没有依赖的更好方法,我会感兴趣.

If there is a better way that does not have dependencies, I would be interested.

这是我的示例输出:

{"data": {"name": "test", "id": "4dCYd4W9i6gHQHvd", "domains": ["www.test.domain.com", "test.domain.com"], "serverid": "bbBdbbHF8PajW221", "ssl": null, "runtime": "php5.6", "sysuserid": "4gm4K3lUerbSPfxz", "datecreated": 1474597357}, "actionid": "WXVAAHQDCSILMYTV"}

推荐答案

如果您有一个可以执行 Perl 兼容正则表达式 (PCRE) 的 grep:

If you have a grep that can do Perl compatible regular expressions (PCRE):

$ grep -Po '"id": *K"[^"]*"' infile.json
"4dCYd4W9i6gHQHvd"

  • -P 启用 PCRE
  • -o 只保留匹配项
  • "id": * 匹配 "id" 和任意数量的空格
  • K 扔掉它左边的所有东西(可变大小正向后视")
  • "[^"]*" 匹配两个引号以及它们之间的所有非引号
    • -P enables PCRE
    • -o retains nothing but the match
    • "id": * matches "id" and an arbitrary amount of spaces
    • K throws away everything to its left ("variable size positive look-behind")
    • "[^"]*" matches two quotes and all the non-quotes between them
    • 如果您的 grep 不能这样做,您可以使用

      If your grep can't do that, you an use

      $ grep -o '"id": *"[^"]*"' infile.json | grep -o '"[^"]*"$'
      "4dCYd4W9i6gHQHvd"
      

      这里使用了两次 grep.第一条命令的结果是 "id": "4dCYd4W9i6gHQHvd";第二个命令删除除了一对引号和它们之间的非引号之外的所有内容,锚定在字符串的末尾 ($).

      This uses grep twice. The result of the first command is "id": "4dCYd4W9i6gHQHvd"; the second command removes everything but a pair of quotes and the non-quotes between them, anchored at the end of the string ($).

      但是,正如所指出的,你不应该为此使用 grep,而是一个可以解析 JSON 的工具 –例如 jq:

      But, as pointed out, you shouldn't use grep for this, but a tool that can parse JSON – for example jq:

      $ jq '.data.id' infile.json
      "4dCYd4W9i6gHQHvd"
      

      这只是 data 对象中 id 键的一个简单过滤器.要去掉双引号,您可以使用 -r(原始输出")选项:

      This is just a simple filter for the id key in the data object. To get rid of the double quotes, you can use the -r ("raw output") option:

      $ jq -r '.data.id' infile.json
      4dCYd4W9i6gHQHvd
      

      jq 还可以漂亮地打印您的 JSON:

      jq can also neatly pretty print your JSON:

      $ jq . infile.json
      {
        "data": {
          "name": "test",
          "id": "4dCYd4W9i6gHQHvd",
          "domains": [
            "www.test.domain.com",
            "test.domain.com"
          ],
          "serverid": "bbBdbbHF8PajW221",
          "ssl": null,
          "runtime": "php5.6",
          "sysuserid": "4gm4K3lUerbSPfxz",
          "datecreated": 1474597357
        },
        "actionid": "WXVAAHQDCSILMYTV"
      }
      

      这篇关于从 JSON 中查找 key 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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