2017-05-19 73 views
0

我比較2個jsons與JSR223斷言,我願意從各個層面從響應JSON刪除的ID刪除ID:的JMeter - 如何從給定的JSON

{ 
    "id" : 52906, 
    "name1" : "559812 Company name1", 
    "name2" : "559812 Company name2", 

    "country" : "DE", 
    "interests" : { 
    "id" : 848675, 
    "description" : false 
    }, 
    "emails" : [ { 
    "id" : 904881, 
    "address" : "[email protected]" 
    } ], 
... 

我使用以下Groovy代碼:

def slurper2 = new JsonSlurper(); 
def jsonResponse = slurper2.parseText(prev.getResponseDataAsString()); 
jsonResponse.rows.findAll { it.remove("id") }; 

但它不起作用 - 請指教。

回答

2

我真的不明白你在哪裏得到這個rows位,因爲我在你的回覆中沒有看到任何名爲「rows」的JSON Array

如果你想刪除所有 「ID」 屬性,你可以用下面的辦法:

def response = prev.getResponseDataAsString() 
def responseWithoutIds = response.replaceAll("\"id\"[ ]*:[^,}\\]]*[,]?", "") 
// do what you need with the modified response, i.e. store it into a JMeter Variable 

vars.put("responseWithoutIds", responseWithoutIds) 

演示:

JMeter replace json attributes

參考文獻:

+0

我用下面的代碼: – Nelly

+0

我用下面的代碼: ' 進口groovy.json.JsonSlurper 進口groovy.json。 JsonBuilder JsonSlurper slurper = new JsonSlurper(); def expected = slurper.parseText(「{\ n」 +「\」name1 \「:\」「+ vars.get(」comp「)+」Company name1 \「,\ n」 +「\」\ name2 \「:\」「+ vars.get(」comp「)+」Company name2 \「,\ n」 +「\」emails \「:[{\ n」 +「\」add​​ress \「: 「」+ vars.get(「comp」)+「@ gmail.com \」\ n「 +」}],\ n「 +」} \ n「); ' – Nelly

+0

def response = prev.getResponseDataAsString() def actual = response.replaceAll(「\」id \「[] *:[^,} \\]] * [,]?」,「」); def expected2 = new JsonBuilder(expected).toPrettyString(); log.info(「ACTUAL =」+ actual); log.info(「EXPECTED =」+ expected2);如果(expected2!= actual){ SampleResult.setSuccessful(false); } 我在jsons中看到的唯一區別是實際中的空格(空行)(其中是刪除了id的行)。所以比較結果失敗。我究竟做錯了什麼? – Nelly

0
import groovy.json.*; 
def s='''{ 
    "id" : 52906, 
    "name1" : "559812 Company name1", 
    "name2" : "559812 Company name2", 

    "country" : "DE", 
    "interests" : { 
    "id" : 848675, 
    "description" : false 
    }, 
    "emails" : [ { 
    "id" : 904881, 
    "address" : "[email protected]" 
    } ] 
} 
''' 

def removeAttr(node, attr){ 
    if(node instanceof Map){ 
     node.remove(attr) 
     node.each{ k,v-> removeAttr(v, attr) } 
    }else if(node instanceof List){ 
     node.each{ i-> removeAttr(i, attr) } 
    } 
} 

def slurper2 = new JsonSlurper(); 
def jsonResponse = slurper2.parseText(s); 
removeAttr(jsonResponse,"id") 

println JsonOutput.prettyPrint(JsonOutput.toJson(jsonResponse))