skip to Main Content

I’m currently trying to parse out a 6-digit verification code that is being sent in an API request’s response body along with some text.

For example:

GET -> https://api.twilio/com/...

The response body returns something like this:

 "body": "Your code is 123456."    

I’m parsing via JSONpath ($.messages[0].body) and saving that string ("Your code is {number}") as a variable.

I’m trying to figure out how to then take that saved variable and parse out just the set of numbers from the string.

I’ve done a lot of stuff, but this is all new to me and I’m learning as I go.

3

Answers


  1. You can extract the value ‘123456’ from the given JSON object by using a regular expression like so:

    // Assuming you have the JSON object
    const data = {
      messages: [
        {
          body: 'Your code is 123456.',
        },
      ],
    };
    
    // Access the 'body' property in the JSON object
    const messageBody = data.messages[0].body;
    
    // Use a regular expression to extract the number
    const code = parseInt(messageBody.match(/d+/)[0], 10);
    
    console.log(code); // Output: 123456
    Login or Signup to reply.
  2. You can use regex to extract the number: $.messages[0].body.match(/(d+)/)[1]

    const response = {
      messages: [
         {
           body: 'Your code is 123456.'
         }
      ]
    };
    
    console.log(response.messages[0].body.match(/(d+)/)[1]);
    Login or Signup to reply.
  3. If you know the structure of the response will always be consistent, you can use str.splice() to get the specific answer and use Number() to make it a number data type. So if the response is like what you said and you’ve saved the answer to a variable called responseStr. You can do

    let code = Number(responseStr.splice(13, 19)) //expect code = 123456
    

    Since it is always a 6-digit code, the start index (13) and end index of the code (18) will remain the same. The second parameter should be end index + 1 since the splice is exclusive of the index of the second parameter.

    However, if the response may have a different structure but you are sure the code is always a 6-digit verification code, you can use REGEX to find the string and convert it to a number data type. So something like

    let matchArr = responseStr.match(/[0-9]{6}/g) //expect matchArr = ["123456"]
    let code = Number(matchArr[0]) //expect code = 123456
    

    where /[0-9]{6}/g is the regex for 6-digit number. But you’ll need to make sure it is the only number of 6-digit or more in the response or matchArr will contain all the combination of substrings that is a 6-digit number or you will need to modify the REGEX to create a more specific match.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search