【问题标题】:Regex to extract UUID without key value in json正则表达式提取 json 中没有键值的 UUID
【发布时间】:2019-12-26 12:17:32
【问题描述】:

我有下面的 json,我想从中提取 '07199fca-b43f-4e58-b0fc-c1e254f34ac0' 值。我在regex101 中获得了多个正则表达式,但每次我获得所有 UUID 值时,我都会以任何方式获得没有 json 键分配的唯一值。

JSON 语法:

    [
  [      
    {
      "clientId": 178,      
      "uniqueId": "5f7f919f-7e0f-4a1e-9a91-89b673896da6",
      "displayName": "Automation Client Test",      
      "productVersion": "7.9.0.0"
    },
    {
      "clientId": 1206,      
      "uniqueId": "096b3549-6899-4621-854c-e682aeb543bd",
      "displayName": "TestClient1",
      "productVersion": "7.9.0.0"
    },
    {
      "clientId": 1356,
      "uniqueId": "faad0e20-dd29-4146-8a8f-37648749aa4e",
      "displayName": "Client Automation",
      "productVersion": "7.9.0.0"
    }
  ], 
  "07199fca-b43f-4e58-b0fc-c1e254f34ac0"
]

【问题讨论】:

  • 请发布您正在使用的正则表达式。
  • 如果 JSON 文档的结构一致,您只能使用正则表达式从 JSON 文档中提取数据 - 否则(可证明数学上)不可能完成。你没有使用 JSON 库有什么原因吗?
  • 我正在使用 '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0- 9]{4}-[a-f0-9]{12}' 正则表达式,但它也给出了 'uniqueId' 值,但我不需要。我必须使用正则表达式提取器来获取这个值。我可以使用 JSR223 脚本,但我想让我的 jmeter 脚本简单

标签: json regex http jmeter request


【解决方案1】:

从您的问题来看,并不是 100% 清楚您在寻找什么,但 if 您正在寻找列表中也满足 [a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12} 正则表达式的最后一个元素(带有引号) ,那么:

(?:['"])([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})(?:['"]\s*]\s*$)

See Regex Demo

  1. (?:['"]) 匹配 '"
  2. ([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}) 捕获组 1 中捕获的正则表达式。
  3. (?:['"]\s*]\s*$) 匹配 '" 后跟 0 个或多个空白字符,后跟一个 ],后跟 0 个或多个空白字符,后跟字符串结尾。

代码:

import re

s = """    [
  [
    {
      "clientId": 178,
      "uniqueId": "5f7f919f-7e0f-4a1e-9a91-89b673896da6",
      "displayName": "Automation Client Test",
      "productVersion": "7.9.0.0"
    },
    {
      "clientId": 1206,
      "uniqueId": "096b3549-6899-4621-854c-e682aeb543bd",
      "displayName": "TestClient1",
      "productVersion": "7.9.0.0"
    },
    {
      "clientId": 1356,
      "uniqueId": "faad0e20-dd29-4146-8a8f-37648749aa4e",
      "displayName": "Client Automation",
      "productVersion": "7.9.0.0"
    }
  ],
  "07199fca-b43f-4e58-b0fc-c1e254f34ac0"
]"""

m = re.search(r"""(?:['"])([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})(?:['"]\s*]\s*$)""", s, flags=re.DOTALL|re.IGNORECASE)
if m:
    print(m[1])

打印:

07199fca-b43f-4e58-b0fc-c1e254f34ac0

【讨论】:

    【解决方案2】:

    JSON 是一个结构良好的数据,使用正则表达式解析 JSON 不是最好的主意,我宁愿推荐使用 JSON Extractor 代替

    相关的JsonPath 查询就像$[1] 一样简单

    演示:

    更多信息:API Testing With JMeter and the JSON Extractor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多