Home > Enterprise >  Find all ocurrences after specific string in another string
Find all ocurrences after specific string in another string

Time:10-10

I have a response from an API (actually is a composite message from AWS lex) and it look like this:

 '{\"messages\":[{\"type\":\"PlainText\",\"group\":1,\"value\":\"Great!\"},{\"type\":\"PlainText\",\"group\":2,\"value\":\"Please click here.\"}]}'

I can't change the response to a string, and I need to get from that string the text of:

"Great!" and "Please click here."

Basically anything after => "value\":\" and before \"}

I have tried plenty of approaches but couldn't hit the nail. Is there any way to do this, I even tried writing a regex but what I could get was the string before and not the actual text I need.

CodePudding user response:

We can use JSON.parse to convert your JSON API output to a JS object. Then, we can iterate all messages in the array and extract the values.

var input = '{\"messages\":[{\"type\":\"PlainText\",\"group\":1,\"value\":\"Great!\"},{\"type\":\"PlainText\",\"group\":2,\"value\":\"Please click here.\"}]}';
var x = JSON.parse(input);
var arr = x.messages.map(item => item.value)
console.log(arr);

CodePudding user response:

Why won't you just use JSON.parse()?

const responseJson = '{"messages":[{"type":"PlainText","group":1,"value":"Great!"},{"type":"PlainText","group":2,"value":"Please click here."}]}';
const response = JSON.parse(responseJson);
const values = response.messages.map(message => message.value);

// values is now ['Great!', 'Please click here.']
  • Related