locked
Unexpected token  in JSON at position 0 error on double quotes (") but works on single quote (') RRS feed

  • Question

  • User-687613544 posted

     var entries = JSON.parse(data);   where  data = "{"locale_prompt": "test"}"   throws an exception  (double quote)

    the error message is : Unexpected token in JSON at position 0 .

    notes : data = "{"locale_prompt": "test"}" and is retrieved from ressouce file  :  {"locale_prompt": "test"}  
    but if I hardcode data = '{"locale_prompt": "test"}' it works fine  (single quote)

    How to fix it  ?

    Best regards

    Saturday, December 9, 2017 7:43 PM

All replies

  • User475983607 posted

    Well, by definition JSON.parse() takes a string.

    How to fix it  ?

    Just use the object as is...

     var entries = data;

    Or just 

    data

    Saturday, December 9, 2017 9:46 PM
  • User283571144 posted

    Hi mously,

    var entries = JSON.parse(data);   where  data = "{"locale_prompt": "test"}"   throws an exception  (double quote)

    the error message is : Unexpected token in JSON at position 0 .

    notes : data = "{"locale_prompt": "test"}" and is retrieved from ressouce file  :  {"locale_prompt": "test"}  
    but if I hardcode data = '{"locale_prompt": "test"}' it works fine  (single quote)

    How to fix it  ?

    According to your description, I suggest you could try to use javascript slice method to remove the first double quote and the last double quote.

    More details, you could refer to below codes:

        <script>
             
            $(function () {
                var data = '"{"locale_prompt": "test"}"'
                data = data.slice(1,-1)
                var entries = JSON.parse(data);
                alert(entries.locale_prompt)
            });
    
        </script>

    Result:

    Best Regards,

    Brando

    Wednesday, December 20, 2017 9:20 AM