2016-12-01 91 views
0

我對jmeter有奇怪的情況。假設我們有一個JSON數組,像這樣的元素:從JMeter Json路徑中獲取json數組中的隨機元素索引後處理器

{ 
    "id" : 123456, 
    "name": "TEST" 
} 

所以我想從陣列上,id隨機元素。對於這種情況下,我使用Json Path PostProcessor這樣的表達式$.elements[?(@.id)]

但由於某些原因,我需要這個元素的索引。因此,我可以創建BeanShellPostProcessor生成隨機索引,然後使用相同Json Path PostProcessor,並使用表達式$.elements[${PARAM_ElementIndex}]。 但在某些情況下,這種陣列可以是空的,Json Path PostProcessor西港島線失敗,這樣的例外: jmeter.extractor.json.jsonpath.JSONPostProcessor: Error processing JSON content in PARAM_ResumeId, message:No results for path: $['elements'][0]['id']

所以可能是有人能提出任何解決方案

回答

1

我會建議,而不是BeanShell中使用Groovy爲:

  • 乖巧的Groovy腳本可以編譯成字節碼,因此性能會更高
  • Groovy具有內置的JSON支持

所以給你JSON響應,如:

import groovy.json.JsonSlurper 

import java.util.concurrent.ThreadLocalRandom 

String response = prev.getResponseDataAsString() 

def jsonSlurper = new JsonSlurper() 
def json = jsonSlurper.parseText(response) 

int size = json.elements.size 

if (size > 0){ 
    def randomIndex = ThreadLocalRandom.current().nextInt(size) 
    def value = json.elements.get(randomIndex).id 
    log.info('Index: ' + randomIndex) 
    log.info('Value: ' + value) 
} 

演示:

{ 
    "elements": [ 
    { 
     "id": 123456, 
     "name": "TEST" 
    }, 
    { 
     "id": 7890, 
     "name": "TEST2" 
    } 
    ] 
} 

您可以使用在JSR223後處理器下面的例子Groovy代碼的指數沿着提取隨機ID

Groovy JSON JMeter

參考文獻:

相關問題