【问题标题】:json path expression to get root key获取根键的json路径表达式
【发布时间】:2020-06-10 12:37:13
【问题描述】:

我有这个 json:

{
    "-1":     {
        "description": "test1"
    },
    "222":     {
        "description": "test2"
    },
    "223":     {
        "description": "test3"
    },
    "224":     {
        "description": "test4"
    },
    "recordsCount": 4
}

使用这个 Json 路径表达式:$.. 它返回所有的 Json。 我想找到只返回 ID 值的 Json 路径表达式: “-1” “222” “223” “224”

你能帮帮我吗?

【问题讨论】:

  • 您需要提供有关您的问题或查询的更多详细信息或代码 sn-p。以便他人更清楚地了解您的问题并努力更清楚地回答您的问题
  • 编辑了描述

标签: json jmeter json-path-expression


【解决方案1】:

访问property(键)而不是值是original JSONPath specifications 中不存在的功能,并且只有少数实现支持此功能。因此,使用 JMeter JsonPath Plugin/Extractor 仅提取属性名称并不走运。
例如,JavaScript 的 JsonPath-Plus 提供运算符 ~ 用于获取匹配项的属性名称。

作为替代方案,您可以使用 JSR223 Groovy 从 JSON 中获取结果:

import groovy.json.JsonSlurper;
import groovy.json.JsonOutput; //if output as JSON is needed

JsonSlurper JSON = new JsonSlurper ();
jsonResponse = JSON.parseText(prev.getResponseDataAsString());
//println json.keySet() //[-1, 222, 223, 224, recordsCount]
vars.put("firstName", response.members[2].firstName.toString());
Set<String> keySet=obj.keySet();
List<String> keys = [];
// iterate over the key set, adding only numbers to result list
for(String key:keySet){
    if(key.isNumber())
        keys.add(key);
}
//println(keys); //[-1, 222, 223, 224]
def output = JsonOutput.toJson(keys); //convert to JSON string if neede
//println(output); //["-1","222","223","224"]
vars.put("jsonKeys", output.toString());

演示:Online Groovy sample.

更多信息:

【讨论】:

  • 很遗憾我不能使用 JSONPath-Plus
  • 那你使用哪种实现/编程语言?
  • 我正在使用 jmeter v.5.3
  • @sarjaana 看起来您可以使用 Groovy 来执行此操作。查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 2014-11-20
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
相关资源
最近更新 更多