我的jsonpath表达式只返回一个结果时会返回两个结果

时间:2018-10-03 03:42:36

标签: ruby jsonpath

这段红宝石代码返回[1,1],但我希望得到的只是[1]。如果我通过http://jsonpath.com放置相同的文本和jsonpath表达式,则得到[1]。这是'jsonpath'宝石中的错误吗?

require 'jsonpath'

string = <<-HERE_DOC
[
    {"processId":1,"process":"XX"},
    {"processId":2,"process":"YY"}
]
HERE_DOC
jsonpath = "$..[?(@.process=='XX')].processId"

path = JsonPath.new(jsonpath)
result = path.on(string)
puts "result: #{result}"

1 个答案:

答案 0 :(得分:1)

问题似乎是多余的,在没有这两种行为的jsonpath表达式中,您只需要向下走一步:

[1] pry(main)> require 'jsonpath'
=> true
[2] pry(main)> jsonpath = "$.[?(@.process=='XX')].processId"
=> "$.[?(@.process=='XX')].processId"
[3] pry(main)> path = JsonPath.new(jsonpath)
=> #<JsonPath:0x00007f8c5bf42f10
 @opts={},
 @path=["$", "[?(@.process=='XX')]", "['processId']"]>
[4] pry(main)> string = <<-HERE_DOC
[4] pry(main)* [
[4] pry(main)*     {"processId":1,"process":"XX"},
[4] pry(main)*     {"processId":2,"process":"YY"}
[4] pry(main)* ]
[4] pry(main)* HERE_DOC
=> "[\n    {\"processId\":1,\"process\":\"XX\"},\n    {\"processId\":2,\"process\":\"YY\"}\n]\n"
[5] pry(main)> result = path.on(string)
=> [1]

jsonpath web example