最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Json object reflection - Stack Overflow

programmeradmin0浏览0评论

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];
 }
发布评论

评论列表(0)

  1. 暂无评论