0

Hi I am trying to compute the average in a function and fetching values from a json obj. Can anyone please tell where am I wrong here. I am sure there is something wrong with the average function. http://jsfiddle.net/NLaSJ/

var json = '[{  "firstName"  : "Stone", "lastName" : "Carpentar", "Salary1" : "600", "Salary2" :  "200" "}, {"firstName":"Samson", "lastName":  "Sears", "Salary1" :  "200", "Salary2":"500"}]';

var emp = JSON.parse(json);
for (var i = 0; i < emp.length; i++) {
    var msg = emp[i];
    var div = document.createElement('div');
    div.innerHTML = msg.firstName + '&nbsp' + msg.lastName + '&nbsp' + msg.Age + '&nbsp' + 'AverageSalary' + computeAverage(msg.salary1, msg.salary2);

    document.body.appendChild(div);

}


function computeAverage(msg.salary1, msg.salary2) {
    return (msg.salary1 + msg.salary2) / 2;
}

Thanks

3
  • it should be function computeAverage(salary1, salary2) Commented Dec 11, 2011 at 20:04
  • not sure how to access the json data in the function Commented Dec 11, 2011 at 20:06
  • Use Firebug or Chrome debugger to find errors. Localize errors by putting in debug statements or commenting out lines. You have an extra quote in the json: "Salary2" : "200" " < - here. Commented Dec 11, 2011 at 20:11

1 Answer 1

1

Your JSON uses "Salary1" and "Salary2", but your code is all lower-case. JavaScript (and JSON) are case-sensitive.

Also, your "computeAverage()" function declaration is syntactically wrong.

Also, your JSON string has a stray double-quote character in it.

Also, in your JSON the numeric values are quoted like strings, and they should not be.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Pointy. I fixed those issue but still I am not getting the expected result. I guess the computeAverage is not executed as expected. jsfiddle.net/NLaSJ/17
thanks I guess that was the issue. I just started learning JSON and the first place I went was w3schools and they were including the values like strings. but anyways thanks a ton
It's a good idea to avoid w3schools :-) StackOverflow is a great resource too of course.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.