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

如何在JavaScript中提取字符串内嵌套JSON?正则转换遇阻求助

Fixing JSON Extraction in JavaScript (Instead of PHP's Recursive Regex)

Got it, let's tackle this problem! The issue you're hitting is that JavaScript's regex engine doesn't support the (?R) recursive pattern syntax that works in PHP and RegEx 101. No worries though—we've got two solid solutions for you: a modified regex that simulates recursion, and a more reliable non-regex approach that actually validates the JSON.

Solution 1: Modified Regex for Nested Braces

Since JS can't use (?R), we can simulate recursion using a captured group and backreference to that group. This regex will match balanced nested curly braces, which covers most valid JSON structures:

const txt = draft.content; // Your long text string
// Simulate recursive matching with a captured group backreference
const jsonPattern = /\{(?:[^{}]|(\{(?:[^{}]|(?1))*\}))*\}/g;
const matches = txt.match(jsonPattern);

// Output the matched JSON-like blocks
console.log(matches);

Note on This Regex

This will work for well-formed nested braces, but it has a limitation: it doesn't account for valid JSON edge cases like escaped quotes containing curly braces (e.g., "key": "value with {curly} braces"). If your input has those, this regex might misfire.

Solution 2: Non-Regex (and More Reliable) JSON Extraction

For a foolproof approach, we can manually track brace depth and validate each candidate block with JSON.parse()—this ensures we only extract valid JSON, not just random nested braces. Here's the code:

function extractValidJSONs(text) {
  const validJSONs = [];
  let braceDepth = 0;
  let startPosition = -1;

  for (let i = 0; i < text.length; i++) {
    const char = text[i];
    
    if (char === '{') {
      if (braceDepth === 0) {
        startPosition = i; // Mark start of a potential JSON block
      }
      braceDepth++;
    } else if (char === '}') {
      braceDepth--;
      
      // When we return to depth 0, we have a complete brace block
      if (braceDepth === 0 && startPosition !== -1) {
        const candidate = text.slice(startPosition, i + 1);
        try {
          // Validate it's actual JSON
          JSON.parse(candidate);
          validJSONs.push(candidate);
        } catch (error) {
          // Not valid JSON—skip it
          continue;
        }
        startPosition = -1;
      }
    }
  }
  
  return validJSONs;
}

// Usage example
const txt = draft.content;
const results = extractValidJSONs(txt);
console.log(results);

Why This Is Better

This method handles all valid JSON edge cases, including escaped characters in strings, and only returns blocks that are actually parsable as JSON. It's way more reliable for real-world text inputs.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:14:06