1

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.

deefour
  • 34,974
  • 7
  • 97
  • 90
VenkatK
  • 1,295
  • 1
  • 9
  • 21
  • can you try this `JSON.parse(errorMessages.replace(/"/g,'"'));` – renakre Apr 15 '15 at 13:06
  • @erkaner, Ohh.. !Thank you so much. But this is only the way or any direct method available in jQuery? Can you suggest of you know any? – VenkatK Apr 15 '15 at 13:08
  • the actual data is coming from a ruby object right. Can you try for obj.html_safe or JSON.parse(obj) on ruby object itself – Sagar.Patil Apr 15 '15 at 13:10

3 Answers3

2

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

Community
  • 1
  • 1
Alexey
  • 3,607
  • 8
  • 34
  • 54
1

Do you use JSON.stringify to get your json object? JSON.stringify may prevent &quot;

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

JSON.parse(errorMessages.replace(/&quot;/g,'"'));
renakre
  • 8,001
  • 5
  • 46
  • 99
  • That should work, but that is a hard approach. If OP is passing such a string, then all special characters will have this format. Parse all of them? – Alexey Apr 15 '15 at 13:08
0

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 = '[&quot;Password first character can not be blank&quot;, &quot;Current password can&#39;t be blank&quot;]';

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

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