0

I have parsed the below string but it s not parsed because of the character ('****'),

JSON.parse("{\"data\":\"value \"}")

It throws error,

Uncaught SyntaxError: Unexpected token in JSON at position 15

How can i get rid of this.

Note: In my case i need to skip all the special characters, which came dynamically. So i need to generic solution. Can i make it?

enter image description here

Shanmu_92
  • 835
  • 1
  • 7
  • 20
  • can you pass it not escaped? are you reading it from DB? – Tamar Jun 23 '17 at 11:20
  • I'm reading the _excel file (Which may or may not contains these type of special characters)_ from server side and return the json string to client side, then i'll convert the json string into object. – Shanmu_92 Jun 23 '17 at 11:24
  • 1
    You could do a replace of any non utf 8 character before you do the parse. Try the regex from here: https://stackoverflow.com/a/20856346. JSON.parse("{\"data\":\"value \"}".replace(/[^\x00-\x7F]/g, "")) – Bryan Euton Jun 23 '17 at 11:28

1 Answers1

1

It seems some special characters are coming from excel file. Try this,

<script type='text/javascript'>
        window.onload = function () {
            var str ='{\"data\":\"value \ \"}'.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
            var d = JSON.parse(str);
            alert(d.data);
        }
    </script>
Matt
  • 1,953
  • 1
  • 19
  • 42
  • The Special character not showing in this post for some reason, so i have attached image of it.. Please refer that image. – Shanmu_92 Jun 23 '17 at 11:29