0

I have below output in json coming from a web method.

{"d":"[{\"id\":1,\"username\":\"deepak_nhm\",\"companyid\":4,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Deepak\",\"lastname\":\"Kerai\",\"avatarsmall\":\"/images_webdev/profile/634596544067649211654527189.jpeg\",\"company\":\"Orange\",\"CompanyRank\":1,\"OverAllRank\":3},{\"id\":2,\"username\":\"Mona_Co\",\"companyid\":1,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Mona\",\"lastname\":\"Sadhu\",\"avatarsmall\":\"/images_webdev/profile/AspNetForumAvatarguy35.jpg\",\"company\":\"3 Retail\",\"CompanyRank\":1,\"OverAllRank\":3}]"}

How do I render the above output, as the below attempt only returns 'undefined')?

  <script type="text/javascript">
    $(document).ready(function () {
        GetProducts();
    });
    function GetProducts() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetContestants",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                // Replace the ul's content with the page method's return.
                var invoices = msg.hasOwnProperty("d") ? msg.d : msg;
                var invoicesInList = [];
                for (var i = 0; i < invoices.length; i++) {
                    invoicesInList.push("<li>" + invoices[i]["username"] + "</li>");
                    //console.log(msg.length);
                }
                $(invoicesInList.join("")).hide().appendTo("#ProductsList").fadeIn("slow");
            }
        });
    }
</script>

Thanks in advance.

1
  • 2
    The JSON seems to be double-encoded. Instead of trying to read malformed JSON you should instead fix the server-side code that creates it. Commented Aug 5, 2013 at 18:59

1 Answer 1

1

msg.d is actually json, so you have to decode it to use it as an object, something like

var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;
Sign up to request clarification or add additional context in comments.

1 Comment

better yet, fix the outer json so as not to contain a json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.