首页 > 解决方案 > 如何在 json 中存储格式化的字符串

问题描述

我正在尝试使用一个文档存储,它要求我以有效的 json 格式存储我的数据。在我的情况下,其中一个字段是邮件合并文本的文本,它具有单引号和双引号以及大括号,如下例所示。

Hi {{ first_name | fallback: "there" }},

I gave you a call for our scheduled appointment today but wasn't able to reach you. I'm still 
happy to chat, so let's get a new time on the calendar. Send a few new times that work for you and I’ll give you a ring.

Thanks,

{{ my_first_name | fallback: "" }}

想知道是否有一个函数可用于转义文档以使其成为有效的 json,以便在我读取它进行处理时将其保存并转换回没有转义字符的纯字符串。

标签: javascriptnode.jsjson

解决方案


JSON.stringify 可以处理任何字符串。

const weirdChars = `Hi {{ first_name | fallback: "there" }}`;
const doc = { text: weirdChars };
const docStr = JSON.stringify(doc);

推荐阅读