VenkatK
VenkatK

Reputation: 1305

How to extract the array from the string which is a JSON response

I am getting the following response from the JSON which is in the string format and inside there is an array.

"["Password first character can not be blank", "Current password can't be blank"]"

I tried to extract the my required array object by using the following method.

errorMessages = "["Password first character can not be blank", "Current password can't be blank"]"
jQuery.parseJSON( errorMessages )

But it is not working for me, can anybody please help me?

Thank you in advance.

Upvotes: 1

Views: 74

Answers (3)

renakre
renakre

Reputation: 8291

Do you use JSON.stringify to get your json object? JSON.stringify may prevent "

IF you still have the problem, you may just replace the " with "

JSON.parse(errorMessages.replace(/"/g,'"'));

Upvotes: 1

user2516837
user2516837

Reputation:

Clearly, you are getting working with an output of htmlspecialchars(). You can use this simple function to first decode it and parse it as an array. Therefore, the whole function will be like.

var errorMessages = '["Password first character can not be blank", "Current password can't be blank"]';

function decodehtml(text) {
  return text
      .replace(/&/g, "&")
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .replace(/&quot;/g, '"')
      .replace(/&#39;|&#039;/g, "'");
}

var errorArray = JSON.parse(decodehtml(errorMessages));

Upvotes: 0

Alexey
Alexey

Reputation: 3637

Unless you can pass the data in a way that JS can convert to JSON, you have to use this:

The best way in my opinion is to use the browser's inbuilt HTML escape functionality to handle many of the cases. To do this simply create a element in the DOM tree and set the innerText of the element to your string. Then retrieve the innerHTML of the element. The browser will return an HTML encoded string.

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  return s;
}

Test run:

alert(HtmlEncode('&;\'><"'));

Output:

&amp;;'&gt;&lt;"

This method of escaping HTML is also used by the Prototype JS library though differently from the simplistic sample I have given.

Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here.

Quoted from: Cerebrus' answer

Upvotes: 2

Related Questions