0

here's my jQuery to parse Json result I got back from one of my page.

{"Result":true,"Action":"add"}

$.parseJSON(data) is not parsing it. I need to get Result and Action value.

    $("#favorite").click(function () {

        $.getJSON('/review/favorite/?Id=@(Model.Review.Id)', function (data) {
            var result = $.parseJSON(data);
            alert(result.Action);
            if (result.result == true && result.action == "add") {
                alert("add");
            } else if (result.result == true && result.action == "delete") {
                alert("delete");
            }
        });

        return false;
    });
2
  • 6
    jQuery already parses the json for you, you don't need to do it yourself Commented Mar 14, 2012 at 11:40
  • Like @ori said, getJSON already parses the data into an object. If yo were doing .get() then you'd need to use parseJSON on the data, but since you called .getJSON you don't need to. Commented Mar 14, 2012 at 11:42

3 Answers 3

4

You dont need to call parseJSON, its already done. So use only data.Action.

Also its case-sensitive so its data.Action and data.Result.
(within the if statement above)

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

Comments

1

You can simply do:

var result = data;

The following is redundant $.parseJSON(data);

Comments

0

The others are correct but I thought I'd go into more detail because, well, I'm bored.

JSON (JavaScript Object Notation) is a string representation of JavaScript objects. You do not (usually, at least) directly manipulate JSON data. Rather, you convert it into the JavaScript objects that it represents, manipulate them in JavaScript and then maybe convert it back to JSON again if needs be.

$.parseJSON() is used for this purpose - it converts a JSON string into actual JS objects.

However the getJSON() function is a bit special as it parses the JSON for you and then passes the resulting JSON data to the callback function as the variable "data". This means that you only ever see the actual data - your code doesn't even see the JSON string.

I suppose that the name getJSON is slightly misleading as it doesn't return JSON, it gets JSON, parses it and returns JavaScript objects.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.