首页 > 解决方案 > 如何将 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)
        }
    }
}

标签: javascriptjsonregexstringobject

解决方案


您不能将正则表达式存储在 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);


推荐阅读