如何从给定的JavaScript字符串中提取JSON数据?
从JavaScript字符串中提取JSON数据的几种方法
嘿,这事儿我门儿清!从你给出的这段JS代码字符串里提取目标JSON,有几个实用的办法,我给你一一拆解:
方法一:正则表达式匹配(最安全通用)
因为你的JSON片段是作为MatchesBlock构造函数的第三个参数存在的,我们可以用正则直接匹配从第一个{到最后一个}的内容(刚好对应整个JSON结构):
// 你的原始字符串 const jsStr = 'var block = new MatchesBlock(\'page_competition_1_block_competition_matches_summary_5\', \'block_competition_matches_summary\', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});'; // 匹配完整的JSON片段 const jsonMatch = jsStr.match(/\{[\s\S]*\}/); if (jsonMatch) { const jsonString = jsonMatch[0]; try { // 解析成JSON对象 const jsonData = JSON.parse(jsonString); console.log('提取到的JSON数据:', jsonData); // 如果只需要bookmaker_urls部分,直接取就行 console.log('Bookmaker链接:', jsonData.bookmaker_urls); } catch (error) { console.error('JSON解析失败:', error); } }
说明
\{[\s\S]*\}这个正则的作用是匹配所有以{开头、}结尾的内容,[\s\S]能匹配包括换行在内的任意字符,贪婪模式的*会自动匹配到最后一个闭合的},刚好对应完整的JSON结构。- 这种方法不需要执行任何未知代码,安全性拉满,适合大多数场景。
方法二:利用JS函数构造(适合信任来源的字符串)
如果你完全信任这段字符串的来源(不会有恶意代码),可以把字符串改造成一个返回目标参数的函数,然后执行它来获取JSON:
const jsStr = 'var block = new MatchesBlock(\'page_competition_1_block_competition_matches_summary_5\', \'block_competition_matches_summary\', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});'; // 替换字符串,生成一个返回第三个参数的函数体 const funcBody = jsStr.replace(/var block = new MatchesBlock\((.*),(.*),(.*)\);/, 'return $3;'); try { // 创建函数并执行 const extractJson = new Function(funcBody); const jsonData = extractJson(); console.log('提取到的JSON数据:', jsonData); } catch (error) { console.error('处理失败:', error); }
注意
这种方法会执行字符串中的代码,如果字符串来源不可信,绝对不要用,存在代码注入风险。
方法三:手动括号计数(适合复杂嵌套场景)
如果你的JSON结构嵌套特别复杂,正则的贪婪匹配可能出错,那可以手动计数括号来找到准确的闭合位置:
const jsStr = 'var block = new MatchesBlock(\'page_competition_1_block_competition_matches_summary_5\', \'block_competition_matches_summary\', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});'; // 找到第三个参数的起始位置(第二个逗号之后的第一个{) const secondCommaIndex = jsStr.indexOf(',', jsStr.indexOf(',') + 1); const startIndex = jsStr.indexOf('{', secondCommaIndex); let bracketCount = 1; let endIndex = startIndex + 1; // 遍历字符,计数括号直到匹配 while (bracketCount > 0 && endIndex < jsStr.length) { const char = jsStr[endIndex]; if (char === '{') bracketCount++; if (char === '}') bracketCount--; endIndex++; } const jsonString = jsStr.slice(startIndex, endIndex - 1); try { const jsonData = JSON.parse(jsonString); console.log('提取到的JSON数据:', jsonData); } catch (error) { console.error('JSON解析失败:', error); }
说明
这种方法通过计数{和}的数量来精准定位JSON的结束位置,完全不会受其他无关括号影响,适合极端复杂的嵌套场景。
内容的提问来源于stack exchange,提问作者fantaghiro
相关产品推荐
相关产品推荐

