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 thenJSON.parse('...')
instead! – ThiefMaster Commented May 4, 2012 at 10:03
4 Answers
Reset to default 5For 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
版权声明:本文标题:javascript - Json object reflection - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745562331a2663546.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论