admin管理员组

文章数量:1430696

I am trying to figure out how I can get a property value from a jsonObject by giving a property name

well, let's say I have the object

var jsonObj = eval('{"key1":"value1","key2":"value2"}');

and I want to get a value by using a method

function getPropertyValue(key){
 return jsonObj.key;
}

alert(getPropertyValue("key1"));

I know that I can get the value by using jsonObj.Key but I want to do it by use a method

Is it possible?

I am trying to figure out how I can get a property value from a jsonObject by giving a property name

well, let's say I have the object

var jsonObj = eval('{"key1":"value1","key2":"value2"}');

and I want to get a value by using a method

function getPropertyValue(key){
 return jsonObj.key;
}

alert(getPropertyValue("key1"));

I know that I can get the value by using jsonObj.Key but I want to do it by use a method

Is it possible?

Share Improve this question asked May 4, 2012 at 10:00 profanisprofanis 2,7413 gold badges39 silver badges50 bronze badges 1
  • You shouldn't use plain eval() to parse json. Use json2.js (needed for older browsers, in modern browsers it doesn't do anything and the native JSON support will be used) and then JSON.parse('...') instead! – ThiefMaster Commented May 4, 2012 at 10:03
Add a ment  | 

4 Answers 4

Reset to default 5

For one: Parse your JSON using the correct methods and avoid using eval:

var jsonObj = JSON.parse( '[{"key1":"value1","key2":"value2"}]' );

And your method can look like this:

function getPropertyValue(key){
 return jsonObj[ key ];
}

You can access objects like arrays:

return jsonObj[key];

Try this:

function getPropertyValue(key){
 return jsonObj[key];
}

alert(getPropertyValue("key1")); //will alert value1

If jsonObj.key works, you can parameterize the key thusly:

 function getPropertyValue(key)
 {  
    return jsonObj[key];
 }

本文标签: javascriptJson object reflectionStack Overflow