views:

36

answers:

2

Let's asume that I have json variable:

var json ={"A":"a","B":"b","x":"y","a":"b"}

When I want to refer to A i just write json.A

How to do it when I have key in a variable, ie:

var key = "A";

Is there any function that returns value or null (if key isn't in json)?

+4  A: 

Use bracket notation, like this:

var key = "A";
var value = json[key];

In JavaScript these two are equivalent:

object.Property
object["Property"];

And just to be clear, this isn't JSON specific, JSON is just a specific subset of object notation...this works on any JavaScript object. The result will be undefined if it's not in the object, you can try all of this here.

Nick Craver
+1. Note though that the two forms you mentioned are equivalent _only if the Property is not a reserved word_... of which there are many in JS, and quite a few are unexpected. So in that sense `object["Property"]` is safer. OTOH, `object.Property` has the advantage (when `Property` is known statically) that tools like JSLint can run checks on them.
LarsH
+2  A: 

How about:

json[key]

Try:

json.hasOwnProperty(key)

for the second part of your question (see http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript)

Bobby Jack