【问题标题】:karate : How to set the Json value if object name contains period in an array空手道:如果对象名称在数组中包含句点,如何设置 Json 值
【发布时间】:2026-01-04 13:50:01
【问题描述】:

这是我的 JSON 请求示例代码,您可以看到 #(Paramtervale) 将被 MyValue 替换

Below is the example of the request json and code:
            * request 
    """
            {
          "query": {
            "bool": {
              "must": [
                {
                  "match_data": {
                    "Event.Data.message": "#(Paramtervale)"
                  }
                },
                {
                  "match_data": {
                    "Event.Name": "#(Paramtervale2)"
                  }
                }
              ],
              "filter": {
                "range": {
                  "@timestamp": {
                    "gte": "now-1m"
                  }
                }
              }
            }
          }
        }
            """
* set request.Event.Data.message = myvalue
* set request.{Event.Data.message} = myvalue
* set request.(Event.Data.message) = myvalue

以上方法均无效,请大家帮忙

【问题讨论】:

    标签: json parameter-passing karate


    【解决方案1】:

    这里有 2 种不同的方法,请注意,对于更新 JSON,不再需要 set。当键名中有特殊字符时,使用方括号的方式来引用 JSON 数据:

    * def temp = { 'a.b': 'xxx' }
    * temp['a.b'] = 'yyy'
    * match temp == { 'a.b': 'yyy' }
    
    # using embedded expressions
    * def val = 'yyy'
    * def temp = { 'a.b': '#(val)' }
    * match temp == { 'a.b': 'yyy' }
    

    【讨论】:

    • * Request['Event.Data.message'] = logDataMessage 部分工作。以“Event.Data.message”结尾的参数和值:“MyValue”,所以请求出错了。该值被实际替换,并且它在请求的末尾附加相同的值。
    • 我正在从 call 函数调用/定义 json。像 read('classpath:'query.json')
    【解决方案2】:

    示例代码:

    Feature: Validation
    
        Scenario:
            * def req =
                """
                {
                    "query": {
                        "bool": {
                            "must": [
                                {
                                    "match_data": {
                                        "Event.Data.message": "#(Paramtervale)"
                                    }
                                },
                                {
                                    "match_data": {
                                        "Event.Name": "#(Paramtervale2)"
                                    }
                                }
                            ],
                            "filter": {
                                "range": {
                                    "@timestamp": {
                                        "gte": "now-1m"
                                    }
                                }
                            }
                        }
                    }
                }
                """
            * req.query.bool.must[0].match_data["Event.Data.message"] = "abc"
            * req.query.bool.must[1].match_data["Event.Name"] = "def"
            * print req
    

    【讨论】:

      最近更新 更多