如何从Contentful的富文本JSON中提取纯文本?
从Contentful富文本JSON中高效提取纯文本
问题场景
我在使用Contentful平台时,作者通过富文本编辑器产出内容。现在需要从中提取纯文本,同时保留原JSON用于其他业务操作。当前的富文本JSON结构如下,希望能高效提取出文本内容「This text is important」。目前我用的方法在内容复杂冗长时显得低效又繁琐:
content[0].content[0].map((content) => content.value)
对应的富文本JSON示例:
{ "nodeType": "document", "data": {}, "content": [ { "nodeType": "paragraph", // 可以是段落、图片、列表、嵌入条目 "data": {}, "content": [ { "nodeType": "text", "value": "This text is ", "data": {}, "marks": [] }, { "nodeType": "text", "value": "important", "data": {}, "marks": [ {"type": "bold"} // 可以是加粗、下划线、斜体 ] } ] } ] }
解决方案
1. 自定义递归遍历函数(通用无依赖)
写一个递归函数遍历所有节点,只提取nodeType为text的节点值,不管内容层级多复杂都能适配:
function extractPlainText(richText) { let text = ''; const traverse = (node) => { if (node.nodeType === 'text') { text += node.value; return; } if (node.content) { node.content.forEach(traverse); } }; traverse(richText); return text; } // 使用示例 const plainText = extractPlainText(你的富文本JSON对象); console.log(plainText); // 输出: "This text is important"
2. 用Contentful官方工具包(更便捷)
Contentful提供了专门的@contentful/rich-text-plain-text-renderer包,能自动处理所有富文本节点类型,不用自己写遍历逻辑:
import { documentToPlainTextString } from '@contentful/rich-text-plain-text-renderer'; const plainText = documentToPlainTextString(你的富文本JSON对象); console.log(plainText); // 输出: "This text is important"
这个方法还能自动处理段落分隔、列表换行等场景,输出的纯文本格式更符合阅读习惯。
两种方法都不会修改原JSON,完全可以保留原数据用于其他操作。
内容的提问来源于stack exchange,提问作者zippyford
相关产品推荐
相关产品推荐

