0

I'm getting a JSON list thanks to this function :

$(document).ready(function () { 
        var idContact = @ViewData["IdPhysique"];
        var Url = "/Accueil/DonneListeFonctionContact";
        $.getJSON(Url, { IdContact: idContact }, function (data) {  

        });

});

And I get this JSON:

json screenshot

Now I would like to parse that JSON to an array so I did this:

$(document).ready(function () { 
        var idContact = @ViewData["IdPhysique"];
        var Url = "/Accueil/DonneListeFonctionContact";
        var data = $.getJSON(Url, { IdContact: idContact }, function (data) {  

        });
        var array = JSON.parse(data);
});

But an error appears in Google development tool:

Uncaught SyntaxError: Unexpected token o

Is there an other way to do that ?

1
  • What you want to do with the returning JSON? like show it on a listview etc? Commented Aug 6, 2013 at 12:19

2 Answers 2

4

You don't have to parse it, because jQuery does it for you and passed it to your callback function in the data argument. $.getJSON() does not return the JSON. So:

 $(document).ready(function () { 
    var idContact = @ViewData["IdPhysique"];
    var Url = "/Accueil/DonneListeFonctionContact";
    $.getJSON(Url, { IdContact: idContact }, function (data) {  
        // here data is an array because jQuery already parsed the JSON
        // data.length is what you need to test
    });
 });

EDIT: Also the "JSON" response that you show in your question is not valid JSON. Property names must be double-quoted, and so must string values, so it should be:

[{"IdFonction":734, "LibellFonction":"Clercs"}, ...
10
  • Did you fight hard to get this above the minimum-size limit? Commented Aug 6, 2013 at 12:18
  • oh okay, I didn't know but if i don't parse it into an array, how can I get the length of the list ? Commented Aug 6, 2013 at 12:18
  • 1
    @HubertSolecki data.length; data is already the array you want Commented Aug 6, 2013 at 12:18
  • 1
    umm... you shouldn't be suggesting alerts for debugging Commented Aug 6, 2013 at 12:20
  • @JanDvorak - Actually even before I realised the OP was trying to use the return value of $.getJSON() my initial short response was above the minimum size without me thinking about it. Regarding the alert (which I've now removed, sigh) that was just the first thing that came to mind to demonstrate that you can use data.length. Commented Aug 6, 2013 at 12:21
0

It is already an array since you get it as JSON. You do not need to JSON.parse it!

2
  • Isn't this exactly what nnnnnn had just said? Commented Aug 6, 2013 at 12:19
  • @JanDvorak Sorry, i hadn't noticed that since i was editing while nnnnnn posted it! Commented Aug 6, 2013 at 12:33

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.