javascript - 如何将 JSON 中的正则表达式传递给 API?

标签 javascript json regex string object

如何在不对其进行字符串化的情况下将 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);

关于javascript - 如何将 JSON 中的正则表达式传递给 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471002/

相关文章:

javascript - 如何同步包含克隆元素的 jquery 可排序列表?

使用 HttpPost 进行 Android-Django 通信

javascript - 带有 JSON 数据的 AngularJS 多维数组

php - c2a0 和 20 字符串比较

c++ - 如何将 boost::filesystem::directory_entry::path() 值分配给字符串?

python - 在 Pandas 数据框中汇总列 block - 按行方式

javascript - 无需单击按钮即可在 TWebBrowser(Google map )中显示位置

javascript - 定义变量的属性

javascript - 在 body 标签内声明函数会导致 "Function not defined"

javascript - 将我的 php 数组转换为等效的 jQuery 数组