1

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);
saravanan
  • 21
  • 1
  • 4

3 Answers3

1

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

String code = accountId.get("code");
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • I got below error when i tried above Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import com.eclipsesource.json.JsonObject; String jsonString = prev.getResponseD . . . '' : Typed variable declaration : Class: JsonObject not found in namespace – saravanan Nov 09 '18 at 06:01
  • did you have JSON library in your class path? – Ryuzaki L Nov 09 '18 at 06:03
  • yes i have minimal-json-0.9.2.jar in lib of my jmeter, and also i have imported below import import com.eclipsesource.json.JsonObject; – saravanan Nov 09 '18 at 06:13
  • https://stackoverflow.com/questions/37855894/error-jmeter-util-beanshellinterpreter-error-invoking-bsh-method-evalsource?rq=1, check this and once again check import statement – Ryuzaki L Nov 09 '18 at 06:31
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:

enter image description here

More information:

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
0
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);