JSON 路径 - 如何根据子元素查找根元素?

时间:2021-02-16 16:34:23

标签: json jsonpath json-path-expression jpath

我有一个 JSON 对象,我正在尝试找到它下面的根元素。有人可以帮我解决这个问题吗?

{
  "store" : {
      "10162021" : {
         "id" : 812340,
         "properties" : {
            "server" : "server1.example.org",
            "serverip" : "",
         }
      },
      "10162022" : {
         "properties" : {
            "serverip" : "127.0.0.1",
            "server" : "server2.example.org",
         },
         "id" : 859480
      }
   }
}

我需要根据服务器名称提取根元素1016202210162021

我尝试使用如下语法,但没有成功

$..*..[?(@.server == server2.example.org)]

我会感谢任何建议。

1 个答案:

答案 0 :(得分:1)

不清楚您是要返回键“10162022”等还是值,例如:

{
   "properties" : {
       "serverip" : "127.0.0.1",
       "server" : "server2.example.org"
   },
   "id" : 859480
}

如果你想返回值,下面的 JSONPath 应该可以工作:

$.store[?( @.properties.server=="server2.example.org" )]

如果您想归还密钥,我不确定这是否可行。 JSONPath 并不是真正设计用于查找键,而是用于查找值。

如果您需要键,我建议对结构进行预处理以将键作为值存储到对象中,如下所示:

{
  "store" : {
      "10162021" : {
         "__key" : "10162021",
         "id" : 812340,
         "properties" : {
            "server" : "server1.example.org",
            "serverip" : ""
         }
      },
      "10162022" : {
         "__key" : "10162022",
         "properties" : {
            "serverip" : "127.0.0.1",
            "server" : "server2.example.org"
         },
         "id" : 859480
      }
   }
}

然后使用这个 JSONPath:

$.store[?( @.properties.server=="server2.example.org" )].__key