2016-12-04 10 views
2

我有一個jsonPath如下檢查是否在jsonPath任何值重複

{ "book": 
     [ 
      { "category": "reference", 
       "author": "Nigel Rees", 
       "title": "Sayings of the Century", 
       "price": 8.95 
      }, 
      { "category": "fiction", 
       "author": "Nigel Rees", 
       "title": "Sword of Honour", 
       "price": 12.99 
      } 
]} 

並要檢查是否有作者的名字已經得到反覆? 我試圖

$.book[?(@.author=='Nigel Rees')].find(1) 

但是,它總是拋出什麼也沒發現異常,我怎麼能檢查author='Nigel Rees'出現即author='Nigel Rees'有兩本書?

回答

1

如果作者姓名存在,則取決於您計劃做什麼。 如果您只想要作者爲Nigel Reese的對象,則可以使用filter

var booksByNigelReese = book.filter(function(book, index) { 
     return book.author === 'Nigel Reese' 
    }) 

.filter()需要一個函數,它的書和指標,chooes接受或rejcet書成取決於一個新的數組,如果函數的結果是truefalse

+0

其實我使用的是加特林斯卡拉DSL'.check(jsonPath(「$。book [?(@。author =='」+ authorName +「')]」)。find(1))'。我試圖驗證'authorName'不應該重複。我對伯爵感興趣,該字符串重複多少次? –

+0

哦,相同的概念仍然可以堅持。你能過濾數組,然後檢查新數組的長度嗎? – devilfart