当前位置: 首页 > 知识库问答 >
问题:

如何使用beanshell预处理器更新jmeter中的JSON节点值

马梓
2023-03-14

目前,我正在尝试使用 BeanShell 预处理器更新 JSON 响应节点值。

需要帮助转换对象中的JSON响应,然后更新节点值和stringify。

我有以下JSON,我想在Jeter中使用BeanShell预处理器更新OrderTypeId和IsCreentaloff值。我在邮递员中尝试了一个效果很好的解决方案。但在BeanShell脚本中遇到困难。

{"DeliveryCharge":0.0,"ApplyCouponToCart":true,"CartId":6970,"SessionId":"DB84A55E-82A9-4BC9-98E8-2A845FB6893A","StoreId":10061,"UserId":10011690,"AppId":10061,"ListCartItem":[{"CartItemId":55513,"UserId":0,"StoreId":0,"AppId":0,"CartId":6970,"PID":772544,"Pack":1,"ProductId":5712,"ProductImage":"https://s3.amazonaws.com/images.liquorapps.com/sm/000457-TWO-FINGERS-GOLD-TEQUILA.png","ProductName":"TWO FINGERS GOLD","UnitSize":"750 ML","Quantity":1,"UPC":"89540135328","SKU":"1014","CategoryId":2,"TypeId":15,"VarietalId":0,"UnitSizeId":12,"CountryId":7,"RegionId":32,"Price":14.99,"PriceDisplay":"$14.99","OfferPrice":14.99,"OfferPriceDisplay":"$14.99","FinalPrice":14.99,"FinalPriceDisplay":"$14.99","TaxRate":0.066250,"QuantityOrdered":1,"Remark":"","ItemTotal":14.99,"ItemTotalDisplay":"$14.99","FinalItemTotal":14.99,"FinalItemTotalDisplay":"$14.99","ItemTotalSaving":0.00,"ItemTotalSavingDisplay":"","ListDiscount":[],"ListCharge":[],"CartItemCount":0,"Deposit":0.00,"DealId":0,"DealInventory":0,"DealInventoryMessage":"","IsBottleLimitAtRetail":false,"TotalQuantity":1,"IsOfferItem":false,"SuccessMessage":"","ErrorDetail":"","ErrorMessage":"","MessageType":"","MessageTitle":"","TextType":""}],"ListDiscount":[],"ListCharge":[],"CouponCode":"","OrderTypeId":1,"AddressId":0,"PaymentTypeId":0,"TipForDriver":0.00,"ListTipForDriver":[],"SubTotal":14.99,"SubTotalDisplay":"$14.99","TotalSavings":0.0,"TotalSavingsDisplay":"-$0.00","TotalCharges":0.0,"TotalChargesDisplay":"$0.00","TotalValue":14.99,"TotalValueDisplay":"$14.99","SubTotalAfterDsicount":14.99,"SubTotalAfterDiscountDisplay":"$14.99","CartPaymentItemUser":{"UserId":10011690,"StoreId":10061,"AppId":0,"PaymentTypeId":0,"UserProfileId":"","IsDefault":false,"IsCardDefault":false,"Credential1":"","Credential2":"UdVYyaeBH+IBzsetzftdBw==","Credential3":"","IsLive":false},"DoPDate":"01/01/1900","DoPTimeSlot":"","DopUtcStartDate":"","DopUtcEndDate":"","Remark":"","DeliveryTax":0.0,"ShippingCost":0.0,"CartItemCount":1,"IsCredentialOff":false,"IsDeliverySolution":false,"DeliveryFeeMarkUp":0.0,"ShippingTax":0.0,"DeliveryTaxRate":0.0,"IsFromCheckOut":true,"IsUpgradeUser":true,"IsToCallDSP":false,"DeliveryInstruction":"","IsStoreCreditUtilize":false,"OrderRewardCredit":5.00,"OrderRewardCreditDisplay":"-$5.00","OrderTotalWithCredit":0.0,"IsStoreReward":false,"CouponRemark":"","IsShipping":false,"CartTotalQuan":1,"ShippingServiceCode":"","ActualDeliveryCharge":0.0,"EstimatedShippingCost":0.0,"ShippingDeliveryCharge":0.0,"DoordashValidateCustomer":false,"CustomerSessionId":13733,"ConvenienceFee":0.0,"IsDoCalculation":false,"SuccessMessage":"","ErrorDetail":"","ErrorMessage":"","MessageType":"","MessageTitle":"","TextType":""}

我在BeanShell预处理器中尝试过:

var CartGetDetailsObject = prev.getResponseDataAsString();
var jsonData  = JSON.parse(CartGetDetailsObject);
jsonData.OrderTypeId=2;
jsonData.IsCredentialOff=true;
vars.put("vCartGetDetailsObject",JSON.stringify(jsonData));
log.info(vCartGetDetailsObject);

错误日志

2020-04-06 12:56:48,139 INFO o.a.j.e.StandardJMeterEngine: Running the test!
2020-04-06 12:56:48,145 INFO o.a.j.s.SampleEvent: List of sample_variables: []
2020-04-06 12:56:48,153 INFO o.a.j.r.ResultCollector: Folder at F:\Office\Performance Test Cases\BottlecappsJmeterPerformanceScripts\apache-jmeter-5.0\RunScript\Date 6-Apr-2020 125648 was created
2020-04-06 12:56:48,154 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)
2020-04-06 12:56:48,958 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2020-04-06 12:56:48,958 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2020-04-06 12:56:48,958 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error
2020-04-06 12:56:48,958 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=0 perThread=0.0 delayedStart=false
2020-04-06 12:56:48,984 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2020-04-06 12:56:48,984 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2020-04-06 12:56:48,986 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2020-04-06 12:56:48,987 INFO o.a.j.s.FileServer: Stored: F:\Office\Performance Test Cases\BottlecappsJmeterPerformanceScripts\apache-jmeter-5.0\testrundata.csv
2020-04-06 12:56:53,982 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``var CartGetDetailsObject = prev.getResponseDataAsString(); var jsonData  = JSON. . . . '' : Typed variable declaration : Attempt to resolve method: parse() on undefined variable or class name: JSON
2020-04-06 12:56:53,982 WARN o.a.j.m.BeanShellPreProcessor: Problem in BeanShell script. org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``var CartGetDetailsObject = prev.getResponseDataAsString(); var jsonData  = JSON. . . . '' : Typed variable declaration : Attempt to resolve method: parse() on undefined variable or class name: JSON
2020-04-06 12:56:54,645 ERROR o.a.j.p.h.s.HTTPJavaImpl: readResponse: java.io.IOException: Server returned HTTP response code: 400 for URL: https://staging.liquorapps.com/Bcapi/api/Cart/CartUpdate
2020-04-06 12:56:54,645 ERROR o.a.j.p.h.s.HTTPJavaImpl: Cause: java.io.IOException: Server returned HTTP response code: 400 for URL: https://staging.liquorapps.com/Bcapi/api/Cart/CartUpdate
2020-04-06 12:56:54,645 INFO o.a.j.p.h.s.HTTPJavaImpl: Error Response Code: 400
2020-04-06 12:56:57,171 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``var CartGetDetailsObject = prev.getResponseDataAsString(); var jsonData  = JSON. . . . '' : Typed variable declaration : Attempt to resolve method: parse() on undefined variable or class name: JSON
2020-04-06 12:56:57,171 WARN o.a.j.m.BeanShellPreProcessor: Problem in BeanShell script. org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``var CartGetDetailsObject = prev.getResponseDataAsString(); var jsonData  = JSON. . . . '' : Typed variable declaration : Attempt to resolve method: parse() on undefined variable or class name: JSON
2020-04-06 12:56:57,389 ERROR o.a.j.p.h.s.HTTPJavaImpl: readResponse: java.io.IOException: Server returned HTTP response code: 400 for URL: https://staging.liquorapps.com/Bcapi/api/Cart/CartUpdate
2020-04-06 12:56:57,389 ERROR o.a.j.p.h.s.HTTPJavaImpl: Cause: java.io.IOException: Server returned HTTP response code: 400 for URL: https://staging.liquorapps.com/Bcapi/api/Cart/CartUpdate
2020-04-06 12:56:57,389 INFO o.a.j.p.h.s.HTTPJavaImpl: Error Response Code: 400
2020-04-06 12:56:58,364 INFO o.a.j.g.a.Start: Stopping test
2020-04-06 12:56:58,377 INFO o.a.j.t.JMeterThread: Stopping: Thread Group 1-1
2020-04-06 12:56:58,377 WARN o.a.j.t.JMeterThread: Interrupting: Thread Group 1-1 sampler: LoginCustomer
2020-04-06 12:56:58,382 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1
2020-04-06 12:56:58,383 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test
2020-04-06 12:56:58,383 INFO o.a.j.s.FileServer: Close: F:\Office\Performance Test Cases\BottlecappsJmeterPerformanceScripts\apache-jmeter-5.0\testrundata.csv
2020-04-06 12:56:58,385 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)

共有1个答案

暴才俊
2023-03-14

JSON是Web API的标准内置对象,您可以在Postman中运行它,因为Postman是一个电子应用程序(浏览器)。JMeter不是浏览器,因此您不能使用JSON函数。

>

  • 将 JSR223 后处理器添加为返回高于 JSON 的请求的子级
  • 将以下代码放入“脚本”区域:

    def jsonData = new groovy.json.JsonSlurper().parse(prev.getResponseData())
    jsonData.OrderTypeId = 2
    jsonData.IsCredentialOff = true
    vars.put("vCartGetDetailsObject", new groovy.json.JsonBuilder(jsonData).toPrettyString())
    log.info(vars.get('vCartGetDetailsObject'))
    

    更多信息:

      < li>Apache Groovy -解析和生成JSON < li>Apache Groovy -为什么以及如何使用它

  •  类似资料:
    • 我需要测试rest api发布JSON。我尝试使用JMeter通过BeanShell后处理器发布Json数据。但是BeanShell后处理器不工作或者我写不出正确的代码。 我的Json是:{“email”:“selin@xxx.com”,“password”:“123”} 你可以在下面的图片中看到我做了什么。

    • 问题内容: 有没有办法从一个BeanShell前置/后处理器到另一个BeanShell处理器 (它们在同一个线程组中) 引用变量? 如果我在HTTP Request下的BeanShell PreProcessor中创建一个String变量,那么我可以在同一HTTP Request下的BeanShell PostProcessor中使用或引用该变量。 我尝试通过以下方式访问此变量: + HTTP请求

    • 在日志中获取以下错误: 上的方法:getName() 下面是Beanshell后处理器中使用的代码。

    • 我如何使用beanshell后处理器来分析来自每个请求的数据?我需要分析请求,如果请求通过-写入文件,如果请求失败-写入其他文件。任何机构都可以为这种情况编写简单的示例脚本?

    • 如何更正此代码?谢谢

    • > 下面有一个json响应数组,我正在将它放入Jmeter正则表达式提取器变量中。 在这里,我有JSON对象。 在JSON对象中,我们有不同的SKU和相应的数量。 我正在使用一个hashmap从CSV文件中读取值,并更新每个SKU的数量细节,但我的脚本无法将响应取到JMeter中的数组中。 最后,我将分享解析JSON数组时遇到的Jmeter代码和错误 我看到很多帖子建议groovy,我不知道如何使

    • 预处理器元素在采样器发出请求之前执行,如果预处理器附加到采样器元素,那么它将在该采样器元素运行之前执行。 预处理器元素用于在运行之前修改样本请求的设置,或更新未从响应文本中提取的变量。 以下是JMeter提供的所有预处理器元素的列表: JDBC预处理器 JSR223预处理器 RegEx用户参数 BeanShell预处理器 BSF预处理器 HTML链接解析器 HTTP URL重写修饰符 HTTP用户

    • 问题内容: 有人请帮助我如何使用做脚本在预处理一些。 任何最好的网站都可以得到相同的。 提前致谢 SIJO 问题答案: 例如: 首先,您需要选择一种脚本语言。根据JMeter最佳实践,最好使用Groovy 添加HTTP请求并放入“服务器名称或IP” 将JSR223预处理器添加为HTTP请求的子代,并将以下行放入“脚本”区域: 添加查看结果树侦听器并运行测试 检查“请求”和“响应数据”选项卡,并确保