Nikhil Behera
Nikhil Behera

Reputation: 165

How to pass regex expression in JSON to API?

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

Upvotes: 3

Views: 4950

Answers (3)

3limin4t0r
3limin4t0r

Reputation: 21160

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.org)

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

Upvotes: 0

Ram Narayanan
Ram Narayanan

Reputation: 1

You could try encoding and decoding the regex

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

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

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

Upvotes: 4

Related Questions