sagnew sagnew - 1 year ago 66
JSON Question

JSON.parse() returning unexpected token

So the issue I'm having is that when i try to call JSON.parse() on this string, i keep getting an unexpected token. It seems to keep escaping at maker and doesn't understand the []? If anyone could shed some light on this issue that would be greatly appreciated

var x = '[{
,"bowner":"Osgoode Township Historical Society and Museum"
,"title":"Wooden pattern for foundry"
,"titlelink":" 3041?RECORD&UNION=Y"

var result = JSON.parse(x);

Answer Source

The data provided parses just fine:

var x = '[{' +
'"db":"COLLECTIONS"' +
',"sisn":"1093041"' +
',"accession":"2011.285.01"' +
',"bowner":"Osgoode Township Historical Society and Museum"' +
',"title":"Wooden pattern for  foundry"' +
',"titlelink":"    3041?RECORD&UNION=Y"' +
',"maker":[]' +
',"image":"[M3IMAGE]201128501.jpg"' +
',"bookmarked":0' +
',"refd":0' +


So the issue must be that (at least in your example) you are getting a syntax error for trying to assign a multi-line string. Multi-line strings cannot be assigned in that way. Here are some alternatives:

// concatenate each line
var x = '[{' +
  '"db":"COLLECTIONS",' +
  '"sisn":"1093041"' +

// escape each line
var x = '[{ \
  "db":"COLLECTIONS", \
  "sisn":"1093041" \

// template literal it (this snippet will not run in some browsers!)
var x = `[{

If using the "concatenate" technique, make sure to escape any single quotes that might be present in the string (i.e. this is Marcelino\'s answer).

If using the "escape" technique, the string cannot contain a backslash as the escaped backslash will not be properly handled by the JSON.parse (as least as far as I know, if anyone could clarify this, it would be great).

If using the "template literal" technique, make sure the browsers that you are hoping to support (or the js environment) in question has them available, or use a transpiler (i.e. Babel).

I hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download