2014-10-03 53 views
2

使用JsonPath我通過這個文件去一個JSON場的最大值: https://github.com/jayway/JsonPath發現在Java中

但我無法弄清楚如何找到一個特定領域的最大值。 在給定的json中,如果我想知道最昂貴的書的價格怎麼辦?

這裏是JSON:

{ 
    "store": { 
     "book": [ 
     { 
      "category": "reference", 
      "author": "Nigel Rees", 
      "title": "Sayings of the Century", 
      "price": 8.95 
     }, 
     { 
      "category": "fiction", 
      "author": "Evelyn Waugh", 
      "title": "Sword of Honour", 
      "price": 12.99 
     }, 
     { 
      "category": "fiction", 
      "author": "Herman Melville", 
      "title": "Moby Dick", 
      "isbn": "0-553-21311-3", 
      "price": 8.99 
     }, 
     { 
      "category": "fiction", 
      "author": "J. R. R. Tolkien", 
      "title": "The Lord of the Rings", 
      "isbn": "0-395-19395-8", 
      "price": 22.99 
     } 
     ], 
     "bicycle": { 
      "color": "red", 
      "price": 29.95 
     } 
    }, 
    "expensive": 10 
} 

會是什麼jsonpath表達(在Java中)找到了最大的價格爲一本書。這裏的答案應該是22.99。

回答

0

你可以嘗試這樣的事情:

var myArray = JSON.parse(jsonAsString)["book"]; 
var max = myArray .reduce(function(a, b) { 
    return Math.max(a, b.price); 
}, 0); 
0

假設jPathStrB高於JSON的一個StringBuilder。 (編輯:我現在意識到你正在使用另一個jayway jsonpath庫,而不是基於groovy的庫。下面的答案使用JsonPath,它帶有放心並依賴於常規的「max()」方法。)

JsonPath jPath = new JsonPath(jPathStrB.toString()); 
    jPath.prettyPrint(); 
    Float price = jPath.get("store.book.price.max()"); 
    System.out.println("Max price: " + price); 

} 
0

我對這個派對很遲,但從版本2.4.0開始,JsonPath不支持你期望的行爲。

從維護者:

You are trying to apply the function max() to the result of the evaluation. That is not how things work. The function will be applied to each object matching the path.

爲了得到答案,你需要每個路徑手動添加到一個數組:

$.max($.store.book[0].price, $.store.book[1].price, $.store.book[2].price, $.store.book[3].price) 

我認爲,總部設在README文件上,大多數人認爲如果以前的作品,那麼這也應該:

$.max($.store.book[*].price) 

但是,它反而扔S上的錯誤:

Aggregation function attempted to calculate value using empty array 

Issue #191有討論可以追溯到至2016年 還有一個古老的拉請求:https://github.com/json-path/JsonPath/pull/197 ,似乎有this enhancement它,包括在哪裏可以找到它的Maven中心。