Tim Daubenschütz
Tim Daubenschütz

Reputation: 2173

Can't access variables in JSON

i feel so stupid. I got this String:

var myString = "({"week":{"@attributes": "Some stuff"}});";

No i parse it to JSON:

var myobject = JSON.parse(myString);

and then i'm trying to access it via:

myobject.week or myobject["week"]

either way isn't working. What am I doing wrong?

Upvotes: 0

Views: 106

Answers (2)

nakib
nakib

Reputation: 4434

That is not a valid json string. You must remove the () and ;

{"week":{"@attributes": "Some s***"}}

Upvotes: 3

jfriend00
jfriend00

Reputation: 707298

This isn't valid javascript:

var myString = "({"week":{"@attributes": "Some stuff"}});";

because of the invalid use of quotes inside the string.

This would work as a valid javscript string:

var myString = '({"week":{"@attributes": "Some stuff"}});';

And, if you want to parse it with JSON.parse(), you should remove the outer parens and the semicolon like this:

var myString = '{"week":{"@attributes": "Some stuff"}}';
var myobject = JSON.parse(myString);
console.log(myobject.week);

Upvotes: 0

Related Questions