Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Noah Schade
Noah Schade
17,694 Points

JavaScript: 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,716 Points

This 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 (`)