在beanshell脚本中提取json值 [英] Extract json values in beanshell script

查看:583
本文介绍了在beanshell脚本中提取json值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的json,我想使用beanshell脚本提取名字和代码.但是我无法提取值. 请帮助

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代码:

Beanshell Code:

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

推荐答案

首先,您是否了解 JSON提取器?如果不是,请考虑使用它,因为它提供了使用简单的 JSONPath 查询(例如$..code$.. firstname

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

如果您仍然想进行脚本编写,请注意从JMeter 3.1开始,建议使用Groovy 进行任何形式的脚本编写. Groovy是比Beanshell更现代"的语言,它支持所有Java新功能,并且具有很多增强功能在Java SDK之上

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

其中之一是通过 JsonSlurper 类,因此您可以将代码缩短为类似以下内容:

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)

演示:

更多信息:

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

这篇关于在beanshell脚本中提取json值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆