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