Extract json values in beanshell script

不想你离开。 提交于 2021-01-28 05:44:48

问题


This is my json i want to extract firstname and code using beanshell script.But i'm not able to extract the values . Please help

{  
   "code":"HNYC",
   "message":"Sucess",
   "data":{  
      "Employeid":"TGRDH-887",
      "Perosonal":{  
         "Details":{  
            "firstname":"Sam",
            "id":3566,
            "dob":"23/11/1990",
            "Yearofjoing":"2018",
            "Salary":30000,
            "Address":"New Delhi",
            "City":"Delhi"
         }
      }
   }
}

Beanshell Code:

import com.eclipsesource.json.JsonObject;
String jsonString = prev.getResponseDataAsString();  
JsonObject accountId = JsonObject.readFrom(jsonString); 
String code = accountId.getJSONObject("code");   
print("value "+code);

回答1:


First of all, do you know about JSON Extractor? If not - consider using it as it provides possibility to fetch JSON data using simple JSONPath queries like $..code and $.. firstname


If you still want to go for scripting be aware that since JMeter 3.1 it is recommended to use Groovy for any form of scripting. Groovy is more "modern" language than Beanshell, it supports all new Java features and it has a lot of enhancements on top of Java SDK

One of them is built-in JSON support via JsonSlurper class, so you can shorten your code to something like:

def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
String code = json.code
log.info(code)

Demo:

More information:

  • Groovy: Parsing and producing JSON
  • Apache Groovy - Why and How You Should Use It



回答2:


You can get code value directly from JSONObject, since it is property in JSONObject refer

String code = accountId.get("code");



回答3:


JSONObject jsonObject = new JSONObject(jsonString);
JSONObject getData = jsonObject.getJSONObject("data");
JSONObject getPerosonal = getData.getJSONObject("Perosonal");
JSONObject getDetails = getPerosonal.getJSONObject("Details");
Object firstname= getDetails.get("firstname");

System.out.println(firstname);


来源:https://stackoverflow.com/questions/53220485/extract-json-values-in-beanshell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!