javascript - 如何将 JSON 中的正则表达式传递给 API?
问题描述
如何在不对其进行字符串化的情况下将 JSON 中的 RegEx 传递给 API?下面是两个代码,它们引用了我想要的内容以及实际传递给 API 的内容。我不需要转换为字符串化。提前致谢
//JSON I want to pass
{
"data": {
"type": "wood-species",
"attributes": {
"description": "test126",
"abbreviation": /([A - Z])\ w +/ <-REGEX that i want to pass
}
}
}
//JSON that actually pass
{
"data": {
"type": "wood-species",
"attributes": {
"description": "test126",
"abbreviation": {} <-REGEX that actually pass(making regex an empty object)
}
}
}
解决方案
您不能将正则表达式存储在 JSON 字符串中。您需要将其存储为实际字符串并使用RegExp
构造函数在接收端重新创建它(同时切掉前导和尾随斜杠/
)。
const obj = {
"abbreviation": "/([A - Z])\w+/"
};
const stringified = JSON.stringify(obj);
const regex = new RegExp(JSON.parse(stringified).abbreviation.slice(1, -1));
console.log(regex);
推荐阅读
- azure - Azure Functions 中的 Chrome 运行失败:尝试以访问权限禁止的方式访问套接字
- visual-studio - 解决方案文件中的差异
- delphi - Delphi,记录类型属性,记录字段分配:预期分配到记录的本地副本
- architecture - 低延迟,服务器推送。服务器可以有多少个打开的连接?
- c# - C# XML 标记到 csv
- c++ - 在某些但不是所有表面上调用 SDL_GetRGBA 返回垃圾的问题
- python - 无法从列表对象中删除空间
- c# - 如何从插件添加标签助手?
- html - 使用“setAttribute('fxFlex', '25%')”更改组件中的 fxFlex 值在 Angular 6 中不起作用
- spring - 如何使用spring data jpa获取表的列名