1
votes

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);
3
Possible duplicate of extracting json dataSuhas Bachhav
@SuhasBachhav this is java, not javascriptMatsemann

3 Answers

1
votes

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

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

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:

0
votes
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);