如何将textarea输入的每一行内容分别生成独立的JSON对象
解决方案
你拿到的整段HTML内容默认通过\n分隔每行的<p>标签,直接拆分过滤后即可生成你需要的逐行JSON结构,还能单独给每一行设置样式,具体实现如下:
核心逻辑
- 把接口返回的整段HTML字符串按
\n切割为数组 - 过滤数组中的空字符串(排除末尾换行等场景产生的无效空行)
- 遍历数组,以索引+1作为行号,对应HTML片段作为值,生成逐行的JSON对象即可
代码示例
前端JavaScript实现
// 原始返回内容 const rawHtml = "<p>Hello<\/p>\n<p>I am an example<\/p>\n<p>Hello 2<\/p>\n"; // 拆分+过滤空行 const lineArr = rawHtml.split('\n').filter(line => line.trim().length > 0); // 生成目标结构 const res = lineArr.map((item, idx) => ({ [`line ${idx + 1}`]: item })); console.log(res);
Dart适配实现(匹配你当前的解析逻辑)
import 'dart:convert'; import 'package:html/parser.dart' show parse; void main() { Map<String, dynamic> originJson = {"line1": "<p>Hello<\/p>\n<p>I am an example<\/p>\n<p>Hello 2<\/p>\n"}; String rawContent = originJson["line1"] ?? ""; // 拆分过滤空行 List<String> lineList = rawContent.split('\n').where((e) => e.trim().isNotEmpty).toList(); List<Map<String, String>> targetList = []; for (int i = 0; i < lineList.length; i++) { // 单独处理每一行的文本提取、样式设置逻辑 String singleLineText = parse(lineList[i]).documentElement?.text ?? ""; // 这里可以添加你的自定义样式逻辑 targetList.add({"line ${i+1}": lineList[i]}); } print(jsonEncode(targetList)); }
兼容优化
如果后续编辑器升级后返回的HTML不再带换行分隔,可改用正则提取所有<p>标签片段,适配性更强:
// Dart正则匹配示例 RegExp exp = RegExp(r'<p>.*?<\/p>', dotAll: true); Iterable<RegExpMatch> matches = exp.allMatches(rawContent); List<String> lineList = matches.map((m) => m.group(0)!).toList();
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

