JSON.parse() returning unexpected token

时间:2016-07-11 21:39:26

标签: javascript json

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 = '[{
"db":"COLLECTIONS"
,"sisn":"1093041"
,"accession":"2011.285.01"
,"bowner":"Osgoode Township Historical Society and Museum"
,"title":"Wooden pattern for  foundry"
,"titlelink":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y"
,"maker":[]
,"image":"[M3IMAGE]201128501.jpg"
,"bookmarked":0
,"refd":0
}]';

var result = JSON.parse(x);

2 个答案:

答案 0 :(得分:1)

Adding a backslash at the end of each line tells the JavaScript engine that the string will continue to the next line. Please try this:

var x = '[{ \
"db":"COLLECTIONS" \
,"sisn":"1093041" \
,"accession":"2011.285.01" \
,"bowner":"Osgoode Township Historical Society and Museum" \
,"title":"Wooden pattern for  foundry" \
,"titlelink":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y" \
,"maker":[] \
,"image":"[M3IMAGE]201128501.jpg" \
,"bookmarked":0 \
,"refd":0 \
}]';

console.log(JSON.parse(x));

答案 1 :(得分:1)

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":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y"' +
',"maker":[]' +
',"image":"[M3IMAGE]201128501.jpg"' +
',"bookmarked":0' +
',"refd":0' +
'}]';

console.log(JSON.parse(x));

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"' +
'}]';
console.log(JSON.parse(x));

// escape each line
var x = '[{ \
  "db":"COLLECTIONS", \
  "sisn":"1093041" \
}]';
console.log(JSON.parse(x));

// template literal it (this snippet will not run in some browsers!)
var x = `[{
  "db":"COLLECTIONS",
  "sisn":"1093041"
}]`;
console.log(JSON.parse(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!