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

如何从指定JSON响应中提取验证码并赋值给变量?

提取JSON中body字段的验证码并赋值给变量

先修正JSON格式

原JSON里"attachments": ,属于语法错误,需要修正为"attachments": null或直接删除该字段,否则无法正常解析。修正后的JSON如下:

{
  "id": 115084015,
  "from": "help@email.ncloud.com",
  "subject": "Verify Code",
  "date": "2022-12-27 19:53:45",
  "attachments": null,
  "body": "  Verification Code : 9906 Enter the code to sign up!  Keep this code to yourself, and no other action is required. "
}

实现方法(按常用编程语言分)

Python

  1. 解析JSON字符串并提取body内容
  2. 通过正则匹配验证码(两种思路,按需选择)

代码示例:

import json
import re

# 修正后的JSON字符串
json_content = '''
{
  "id": 115084015,
  "from": "help@email.ncloud.com",
  "subject": "Verify Code",
  "date": "2022-12-27 19:53:45",
  "attachments": null,
  "body": "  Verification Code : 9906 Enter the code to sign up!  Keep this code to yourself, and no other action is required. "
}
'''

# 解析JSON数据
parsed_data = json.loads(json_content)
body_text = parsed_data["body"]

# 思路1:精准匹配"Verification Code : "后的数字(避免其他数字干扰)
code_match = re.search(r'Verification Code : (\d+)', body_text)
if code_match:
    verify_code = code_match.group(1)
    print(verify_code)  # 输出:9906

# 思路2:直接匹配连续4位数字(适用于验证码固定为4位的场景)
code_match = re.search(r'\b\d{4}\b', body_text)
if code_match:
    verify_code = code_match.group()
    print(verify_code)  # 输出:9906

JavaScript

  1. 解析JSON字符串并提取body内容
  2. 用正则表达式匹配验证码

代码示例:

// 修正后的JSON字符串
const jsonContent = `{
  "id": 115084015,
  "from": "help@email.ncloud.com",
  "subject": "Verify Code",
  "date": "2022-12-27 19:53:45",
  "attachments": null,
  "body": "  Verification Code : 9906 Enter the code to sign up!  Keep this code to yourself, and no other action is required. "
}`;

// 解析JSON数据
const parsedData = JSON.parse(jsonContent);
const bodyText = parsedData.body;

// 思路1:精准匹配"Verification Code : "后的数字
const regex1 = /Verification Code : (\d+)/;
const matchResult1 = bodyText.match(regex1);
if (matchResult1) {
  const verifyCode = matchResult1[1];
  console.log(verifyCode); // 输出:9906
}

// 思路2:匹配连续4位数字
const regex2 = /\b\d{4}\b/;
const matchResult2 = bodyText.match(regex2);
if (matchResult2) {
  const verifyCode = matchResult2[0];
  console.log(verifyCode); // 输出:9906
}

注意事项

  • 如果body中可能存在其他数字,优先用思路1,精准匹配验证码标签后的内容,避免误提取。
  • 若验证码位数固定,思路2更简洁,但要确保body内没有其他相同位数的无关数字。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:55:25