javascript - Json object reflection - Stack Overflow

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

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];
 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745562332a4633180.html

相关推荐

  • javascript - Json object reflection - Stack Overflow

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

    14小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信