You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wiremock独立版动态响应异常:jsonPath失效返回模板代码问题排查

WireMock独立版jsonPath模板不生效问题解决

我正在使用WireMock独立版,尝试通过jsonPath结合模板生成动态响应,但模板代码直接被原样返回,没有被解析执行。以下是相关信息:

示例请求

{
    "source": "Web",
    "orders":[ 
        {
            "id": "Order1",
            "status": "In Progress"
        },
        {
            "id": "Order2",            
            "status": "In Progress"
        }
    ]    
}

预期响应

{
    "user": "User1",
    "orders": [
        {
            "id": "Order1",
            "status": "In Progress", 
            "shipping": "Pending"
        },
        {
            "id": "Order2",            
            "status": "In Progress",
            "shipping": "Pending"
        }
    ]
}

当前response.json配置

{
    "user": "User1",
    "orders": [
          {{#each (jsonPath request.body '$.batches') as |batches|}}
          {
             "id": "{{{batches.id}}}",
             "status": "In Progress", 
             "shipping": "Pending"
          }{{^last}},{{/last}}
          {{//each}}
    ]
}

实际响应

{
    "user": "User1",
    "orders": [
          {{#each (jsonPath request.body '$.batches') as |batches|}}
          {
             "id": "{{{batches.id}}}",
             "status": "In Progress", 
             "shipping": "Pending"
          }{{^last}},{{/last}}
          {{//each}}
    ]
}

问题排查与修正

  1. 模板语法错误
    你写的循环闭合标签是{{//each}},正确的Handlebars闭合标签应该是{{/each}},多一个斜杠会导致模板无法被正确识别解析。

  2. jsonPath路径错误
    请求中的数组字段是orders,但模板里写的是$.batches,路径不匹配会导致无法取到目标数据,即便模板生效也生成不了正确的数组内容。

  3. 未启用响应模板功能
    WireMock默认不会自动解析模板,需要手动开启:

    • 启动WireMock时添加全局模板参数:java -jar wiremock-jre8-standalone.jar --global-response-templating
    • 或者在单个Stub配置中指定transformer:
      {
        "request": {
          "method": "POST",
          "url": "/your-api-path"
        },
        "response": {
          "bodyFileName": "response.json",
          "headers": {
            "Content-Type": "application/json"
          },
          "transformers": ["response-template"]
        }
      }
      

修正后的response.json

{
    "user": "User1",
    "orders": [
          {{#each (jsonPath request.body '$.orders') as |order|}}
          {
             "id": "{{{order.id}}}",
             "status": "{{{order.status}}}", 
             "shipping": "Pending"
          }{{^last}},{{/last}}
          {{/each}}
    ]
}

内容的提问来源于stack exchange,提问作者user2388556

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:42:44