2

I am working with an crossdomain api that returns a jsonp string. I want to parse it into a javascript object so that it gets easier to work with. I know that with a json string you can just do this:

  success: function (val) {
                    var result = JSON.parse(val);
                }

But if i do that with the jsonp i got from the api i get "Uncaught SyntaxError: Unexpected token o"

Am i doing it wrong or is this not the way to do it with jsonp?

--------EDIT 1--------------------------- This is what my jsonp string looks like if i open it up:

Object {resource: "boxscore", parameters: Object, resultSets: Array[22]}
parameters: Object
resource: "boxscore"
resultSets: Array[22]
0: Object
1: Object
2: Object
3: Object
4: Object
 headers: Array[28]
    0: "GAME_ID"
    1: "TEAM_ID"
    2: "TEAM_ABBREVIATION"
    3: "TEAM_CITY"
    4: "PLAYER_ID"
    5: "PLAYER_NAME"
    6: "START_POSITION"
    7: "COMMENT"
length: 28
__proto__: Array[0]
name: "PlayerStats"
rowSet: Array[26]
    0: Array[28]
        0: "0041300201"
        1: 1610612764
        2: "WAS"
        3: "Washington"
        4: 2772
        5: "Trevor Ariza"
        6: "F"
        7: ""
        8: "37:20"
        9: 7
        10: 10
        11: 0.7
        12: 6
1: Array[28]
2: Array[28]
3: Array[28]
4: Array[28]
5: Array[28]
6: Array[28]

So what i want to do is parse the data with the header-info in each array, how do i do that? So for example if i want GAME_ID i just write GAME_ID and i get the gameid "0041300201" for each array.

4
  • did you console.log your val variable? Commented May 6, 2014 at 19:31
  • yes i have checked it in console.log. Commented May 6, 2014 at 19:40
  • and what did it log.... Commented May 6, 2014 at 19:40
  • It is a massiv jsonp string with a lot of arrays whitin arrays so thats why i want to parse it with headers Commented May 6, 2014 at 19:43

4 Answers 4

1

You can use the jsonp liberary for it .., it will be good if the crossdomain site give the json sting :

go to this link it may be helpful.

http://www.jquery4u.com/function-demos/jsonp/

or you can use the code like


    /* Loading JSON objects using JSONP */
    (function($) {
        var url = 'http://www.jquery4u.com/scripts/jquery4u.settings.json';
        $.ajax({
           type: 'GET',
            url: url,
            async: false,
            contentType: "application/json",
            dataType: 'jsonp'
        });
    })(jQuery);
Sign up to request clarification or add additional context in comments.

3 Comments

How do i do with my variable? Do i send it as data to that url?
Why did you set a contentType? why did you set async to false? neither of these things have any effect on jsonp requests.
please check my second answer $.ajax({ type: "GET", url: "example.com?keyword=r&callback=jsonp", dataType: 'jsonp', jsonpCallback: 'myfunc', // the function to call jsonp: 'callback', // name of the var specifying the callback in the request error: function (xhr, errorType, exception) { var errorMessage = exception || xhr.statusText; alert("Excep:: " + exception + "Status:: " + xhr.statusText); } });
1

If you are getting to the success callback and this is a jsonp call, your val parameter is already a javascript object.

success: function (result) {
    console.log(result);
    console.log(result.someproperty);
}

this explains your error too if result is an object because JSON.parse({}) throws the same error.

SyntaxError: Unexpected token o

which is equivalent to

JSON.parse("[object Object]"); // now you see where `o` came frome

Comments

1

If you're accessing a remote API that supports JSONP and have jQuery available, it's easy to skip the intermediary parsing step:

// Assuming you have jQuery available:
$.ajax('http://example.com/jsonpapi?callback=?', {
  dataType: 'jsonp',
  success: function(data) {
    // No parsing necessary.
    console.log(data);
  }
});

That injects a script element pointing at your JSONP endpoint and the endpoint responds by wrapping the JSON in a call to a function that jQuery defines for you automatically. callback is a relatively standard naming convention for the JSONP callback, but double check what your API expects.

If you don't have jQuery available or don't want to use it, you can define a callback function and inject a script element yourself:

var jsonpCallback = function(data) {
  console.log(data);
};

var s = document.createElement('script');

s.src = 'http://example.com/jsonpapi?callback=jsonpCallback';

document.getElementsByTagName('head')[0].appendChild(s);

That's essentially what jQuery does for you in the JSONP scenario.

4 Comments

see my edit!:) Ive think i made my question more clear:)
@DanielGustafsson: I don't think what you posted is quite right. That's not valid JSON or JSONP. It looks like the text output from dev tools, maybe?
Yes its from chrome devtool. Isn't that the same thing as what i get in my success in the ajax post? @Dave Ward ?
@DanielGustafsson: It's a representation of the same data structure, but not JSON. Since that's indicating that you've already got an object, there's no need to parse it. It's ready to use as is.
-2

may this will solve your problem :

function jsonp(data) {
  alert('jsonp was called');
}

$.ajax({
  url: 'http://jsfiddle.net/echo/jsonp/?callback=jsonp',
  dataType: 'jsonp',
  data: {
    'foo': 'bar'
  },
  success: function(data) {
    console.log(data);
  }
});

Actually, JSONP is not JSON at all, it's just JavaScript code.There's no reason to eval in this case... you could simply do after defining that function globally. jquery also offers ways of making a same-domain jsonp request with a specific jsonp callback if you must use jQuery to do the

// Create the function the JSON data will be passed to.
function myfunc(json) {
  alert(json);
}

$.ajax({
  type: "GET",
  url: "http://example.com?keyword=r&callback=jsonp",
  dataType: 'jsonp',
  jsonpCallback: 'myfunc', // the function to call
  jsonp: 'callback', // name of the var specifying the callback in the request
  error: function (xhr, errorType, exception) {
    var errorMessage = exception || xhr.statusText;
    alert("Excep:: " + exception + "Status:: " + xhr.statusText);
  }
});

4 Comments

you don't need to define a function if you are using jquery, jquery does this for you (and doing so may result in jquery throwing errors). you're just complicating things.
JSON.parse("[object Object]"); you saying about type casting in json object, i can use it for parsing the json but when i mess with the jsonp which is nothing but a js code i need to first convert it into json then i can parse it. neverthless we can also use the jquery method window.alert(JSON.stringify(result));
So there is no good way to pair the header-info with the data in each array @KevinB, and @phpBud? So what i do have to do is make my own object by looking through all the arrays and find the data i want? Like val.resultSets[4].rowSet[1]
You can structure the data however you see fit. I don't understand what you're asking.

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.