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

在Flutter中使用JavaScript HTML DOM提取body内的目标JSON字符串

问题:从HTML响应中提取目标JSON字符串

原始HTML响应

<html><body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{'name':'john doe'}
</body></html>

已尝试操作及问题

  • 调用 document.body.innerHTML,返回结果为 null
  • 调用 document.body.outerHTML,返回内容如下:
<body><pre style="word-wrap: break-word; white-space: pre-wrap;">{'name:'john doe'}</body>

需要提取的目标字符串:{'name':'john doe'}


解决方案

方法1:直接获取pre元素文本

通过DOM选择器定位<pre>元素,提取其文本内容并清理首尾空白:

const preElement = document.querySelector('pre');
const targetStr = preElement.textContent.trim();
console.log(targetStr); // 输出 {'name':'john doe'}

方法2:处理outerHTML字符串

如果只能获取document.body.outerHTML,可通过正则匹配提取目标内容:

const outerHtml = document.body.outerHTML;
const match = outerHtml.match(/<pre[^>]*>([\s\S]*?)<\/body>/);
if (match) {
  const targetStr = match[1].trim();
  console.log(targetStr); // 输出 {'name':'john doe'}
}

额外处理:转为标准JSON

目标字符串使用单引号,不符合标准JSON规范,若需转为JSON对象,可替换单引号后解析:

const standardJson = targetStr.replace(/'/g, '"');
const jsonObj = JSON.parse(standardJson);
console.log(jsonObj.name); // 输出 john doe

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:45:33