admin管理员组

文章数量:1429693

How can I pass RegEx in JSON to API without stringify it? Below is two code that refer what i want and what actually passing to API. I don't need to convert to stringify. Thanks in advance

//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)
        }
    }
}

How can I pass RegEx in JSON to API without stringify it? Below is two code that refer what i want and what actually passing to API. I don't need to convert to stringify. Thanks in advance

//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)
        }
    }
}
Share Improve this question edited Jun 6, 2019 at 4:50 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Jun 6, 2019 at 4:44 Nikhil BeheraNikhil Behera 1651 silver badge9 bronze badges 2
  • 1 Sounds like you're asking why JSON doesn't allow you to store types it does not support. Answer: Because it doesn't support them. Convert it to a string. – Tibrogargan Commented Jun 6, 2019 at 4:47
  • 1 without stringify i think it is not possible , you have to pass as a string – Saurabh Mistry Commented Jun 6, 2019 at 4:47
Add a ment  | 

3 Answers 3

Reset to default 4

You can't store a regex in a JSON string. You'd need to store it as an actual string and recreate it on the receiving end with the RegExp constructor (also slice off the leading and trailing slashes /).

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);

You could try encoding and decoding the regex

const regex = /([A - Z])\w+/
const encodedRegex = encodeURIComponent(regex)
const decodedRegex = decodeURIComponent(encodedRegex);
console.log(decodedRegex);

JSON is a relatively simple data encoding format. It only allows for the types object, array, string, number, and literals, true, false, and null. (See json)

One solution to your issue could be to send the relevant data (pattern & flags) wrapped in an object. To represent an RegExp object you could for example use the structure:

{ "JavaScript/Type": "RegExp", "pattern": "([A-Z])\\w+", "flags": "mu" }

If you are using JavaScript you can use the JSON.stringify() replacer argument to encode your regular expressions. And the JSON.parse() reviver argument to decode your encoded regular expressions. Here is an example:

const dataStructure = {
  data: {
    type: "wood-species",
    attributes: {
      description: "test126",
      abbreviation: /([A-Z])\w+/mu,
    },
  }
};
const json = JSON.stringify(dataStructure, replacer, 2);
const reconstructed = JSON.parse(json, reviver);

console.log("dataStructure = ", dataStructure);
console.log("json =", json);
console.log("reconstructed =", reconstructed);


// JSON encoder/decoder helpers aka replacer/reviver
function replacer(key, value) {
  if (!value) return value;
  switch (value.constructor?.name) {
    case "RegExp": return {
      "JavaScript/Type": "RegExp",
      pattern: value.source,
      flags: value.flags,
    };
    default: return value;
  }
}

function reviver(key, value) {
  if (!value) return value;
  switch (value["JavaScript/Type"]) {
    case "RegExp": return new RegExp(value.pattern, value.flags);
    default: return value;
  }
}

本文标签: javascriptHow to pass regex expression in JSON to APIStack Overflow