Ricardo Rocha
Ricardo Rocha

Reputation: 16266

Unexpected token # in JSON

I'm trying to parse a json string and I'm getting the error:

> Uncaught SyntaxError: Unexpected token # in JSON at position 13
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

Follows the code:

    JSON.parse("{\"chars\":\" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿıŁłŒœŠšŸŽžƒˆˇˉ˘˙˚˛˜˝ΔΩμπ‐–—‘’‚“”„†‡•…‰‹›⁄€™Ω∂∆∏∑−∕∙√∞∫≈≠≤≥◊fifl}")

Upvotes: 1

Views: 543

Answers (1)

Seb Cooper
Seb Cooper

Reputation: 574

The issue is your escaping. You have to escape the double quotes as well as the backslash in the characters value. I removed the second backslash from within the square brackets as this also resulted in a parse error.

Also, to simplify escaping the value to pass to JSON.parse, use JSON.stringify on an object with chars value rather than a constructed string. See: JSON Stringify on MDN

The following restructuring of the characters value works:

var charObj = {chars: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿıŁłŒœŠšŸŽžƒˆˇˉ˘˙˚˛˜˝ΔΩμπ‐–—‘’‚“”„†‡•…‰‹›⁄€™Ω∂∆∏∑−∕∙√∞∫≈≠≤≥◊fifl"}; 

JSON.parse(JSON.stringify(charObj));

Upvotes: 2

Related Questions