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

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

问题描述

我想从这行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查找键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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