Read the statement by Michael Teeuw here.
trouble Accessing JSON structure using variables, help
-
I am trying to access a json structure using variables containing the parts of the structure.
according to the javascript and json docs, when u want to use variables, u must use the bracket notation
so
object[key1][key2].valuewhen object looks like this
{ "fred":{"mary":"value1","sue":value2"} }so
var a='fred' var b='sue'and
object[a][b].value should return 'value2'but in my module, I am getting
cannot access 'sue' of undefined
if I make a variable then it works, but still throws an errorvar bob=object[a][b] returns error cannot access 'sue' of undefinedbut if I do
var bob= object[a.toString()][b.toString()]then it works, and bob= the sue data item and
bob.value works… BUT still throws an error cannot access value of undefined… but it worked (I debug step thru the code)…if I use literals instead of variables as the key names, then it works… but I need to use variables to reduce the code by using a loop to walk thru the big json object…
do we have some downlevel javascript? or??
this should be SO easy, but something is weird…
-
@sdetweil well, its a side effect of the way the code works…
if (object[key][key] !==‘undefined’)
will throw an access error if either of the two keys are not in the object… BEFORE you can check the results with the if…
SO, wrap with try/catch and all is well…
-
You genius types are awesome! :thumbsup:
Create the topic. Reply to yourself. Mark topic solved (by self).
-
@mykle1 there is no better thought motivator than posting on a live forum…!!
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login