Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNoah Schade
17,694 PointsJavaScript: I'm trying to change this string into an array. What is wrong with my code?
localStorage.setItem("savedItems", `[{name:\"Marcus\", select:\"going\", notes:\"Filler text.\"},
{name:\"Tom\", select:\"not going\", notes:\"Has a business meeting so he can't come.\"}]`);
const inviteList = localStorage;
const get = inviteList['savedItems'];
const getArray = JSON.parse(get);
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 PointsThis is the full error that I get:
Uncaught SyntaxError: Unexpected token n in JSON at position 2
Keys in JSON objects must be in quotes, unlike in JavaScript where keys can be in quotes or not. So it's trying to parse this: [{name: ...
and it's running into a problem at the letter n because it doesn't know how to handle the letter n
in this context. It should be like this instead: [{"name":
...
I'm also not sure why you would be needing to pass in a string object hard coded like this in the first place. If you have a JavaScript object, you could convert it to a string with JSON.stringify()
and it would automatically take care of converting it to the right format, with object keys wrapped in quotes. Also, FYI, you're escaping all your quote characters (\"
) but this is unnecessary in this case because the whole thing is a template string wrapped in back ticks (`)
Noah Schade
17,694 PointsNoah Schade
17,694 PointsThank you for your help!
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,735 PointsNo problem.