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

如何在JavaScript中解析嵌套JSON字符串并提取指定字段?

JavaScript解析JSON字符串提取指定字段

步骤说明

你提供的JSON字符串包含嵌套结构,且sub_json字段本身是转义后的JSON字符串,提取目标字段可按以下步骤实现:

  1. 解析外层JSON字符串
    使用JSON.parse()将整个JSON字符串转换为JavaScript对象,就能直接访问嵌套属性:

    // 原始JSON字符串
    const rawJsonStr = `{
        "success": true,
        "data": {
            "record": {
                "ID": "2",
                "user_id": "11",
                "sub_json": "{\"ntest\":\"1234\",\"allthis\":\"stuff\",\"somethingelse\":\"whatever\"}"
            }
        }
    }`;
    
    // 解析外层JSON为JS对象
    const parsedObj = JSON.parse(rawJsonStr);
    
  2. 提取目标字段

    • 直接获取user_id:
      const userId = parsedObj.data.record.user_id;
      console.log(userId); // 输出: "11"
      
    • 获取sub_json:如果只需要原始转义字符串,直接取值即可;如果需要将其转换为可操作的JS对象,需再次调用JSON.parse():
      // 获取原始转义字符串
      const subJsonRaw = parsedObj.data.record.sub_json;
      console.log(subJsonRaw); // 输出: "{\"ntest\":\"1234\",\"allthis\":\"stuff\",\"somethingelse\":\"whatever\"}"
      
      // 转换为JS对象(按需使用)
      const subJsonObj = JSON.parse(subJsonRaw);
      console.log(subJsonObj.ntest); // 输出: "1234"
      

容错处理(可选)

如果原始JSON可能存在格式错误,建议用try-catch包裹解析逻辑,避免代码中断:

try {
   const parsedObj = JSON.parse(rawJsonStr);
   const userId = parsedObj.data.record.user_id;
   const subJsonObj = JSON.parse(parsedObj.data.record.sub_json);
   // 后续业务逻辑
} catch (err) {
   console.error('JSON解析失败:', err);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:03:34