3

I have a response which contains an array which is present inside string(""). What I need I just the array. How do I get rid of the quotes?

I tried JSON.parse(). It gave me error message

SyntaxError: Unexpected token ' in JSON at position 1

What I have is as follows:

email_id: "['abc@mail.com', 'cde@mail.com']"

What I need is as follows:

email_id: ['abc@mail.com', 'cde@mail.com']

This is a key which a part of a large response I am getting from backend in my angular 7 app.

Spring
  • 13,583
  • 4
  • 35
  • 47
Vaishnavi Dongre
  • 215
  • 2
  • 10
  • Use JSON.parse(response.email_id) to parse only email_id – R.K.Saini Sep 25 '19 at 10:44
  • 1
    Possible duplicate of [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes) – MrGeek Sep 25 '19 at 10:45

2 Answers2

3

Below solution will work for your case provided the strings does not contain /'

var a = "['abc@mail.com', 'cde@mail.com', 'def@mail.com']";
a = a.replace(/'/g, '"');
var result = JSON.parse(a);

Considering its an email data, there's no possibility of having that escape character sequence

Mahesh
  • 1,098
  • 15
  • 38
1

You have to send in backend the format with double quotes instead of one quotes or in front just replace quotes ' with double quotes " inside your array , otherwise the parse will fail ,

see below snippet :

let json = {
  email_id:  "['abc@mail.com', 'cde@mail.com']"
}
json.email_id = json.email_id.replace(/'/g,"\"");
console.log(JSON.parse(json.email_id));
Spring
  • 13,583
  • 4
  • 35
  • 47