【问题标题】:how do i parse jsonp to javascript object?我如何将 jsonp 解析为 javascript 对象?
【发布时间】:2014-05-06 19:29:01
【问题描述】:

我正在使用返回 jsonp 字符串的跨域 api。我想将它解析成一个 javascript 对象,以便更容易使用。 我知道使用 json 字符串你可以这样做:

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

但如果我使用从 api 获得的 jsonp 执行此操作,我会得到“Uncaught SyntaxError: Unexpected token o”

是我做错了还是这不是用 jsonp 做的方式?

--------编辑 1--------------- 如果我打开它,这就是我的 jsonp 字符串的样子:

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]

所以我想做的是用每个数组中的 header-info 解析数据,我该怎么做? 因此,例如,如果我想要 GAME_ID,我只需编写 GAME_ID,然后为每个数组获取游戏 ID“0041300201”。

【问题讨论】:

  • 你控制台记录了你的 val 变量吗?
  • 是的,我已经在 console.log 中检查过了。
  • 它记录了什么......
  • 这是一个带有很多数组的大规模 jsonp 字符串,这就是为什么我想用标题解析它

标签: jquery ajax parsing jsonp


【解决方案1】:

你可以使用 jsonp 库..,如果跨域站点提供 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);

【讨论】:

  • 如何处理我的变量?我是否将其作为数据发送到该网址?
  • 为什么要设置 contentType?你为什么将异步设置为假?这些都对 jsonp 请求没有任何影响。
  • 请检查我的第二个答案 $.ajax({ type: "GET", url: "example.com?keyword=r&callback=jsonp", dataType: 'jsonp', jsonpCallback: 'myfunc', // 要调用的函数jsonp: 'callback', // 在请求中指定回调的 var 名称 error: function (xhr, errorType, exception) { var errorMessage = exception || xhr.statusText; alert("Excep:: " + exception + "状态:: " + xhr.statusText); } });
【解决方案2】:

如果您正在获取成功回调并且这是一个 jsonp 调用,则您的 val 参数已经是一个 javascript 对象。

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

如果result 是一个对象,这也解释了您的错误,因为JSON.parse({}) 会引发相同的错误。

SyntaxError: Unexpected token o

相当于

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

【讨论】:

    【解决方案3】:

    如果您正在访问支持 JSONP 并且有 jQuery 可用的远程 API,则可以轻松跳过中间解析步骤:

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

    这会注入一个指向您的 JSONP 端点的脚本元素,并且该端点通过将 JSON 包装在对 jQuery 自动为您定义的函数的调用中来响应。 callback 是 JSONP 回调的相对标准命名约定,但请仔细检查您的 API 期望什么。

    如果你没有 jQuery 可用或者不想使用它,你可以定义一个回调函数并自己注入一个脚本元素:

    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);
    

    这基本上就是 jQuery 在 JSONP 场景中为您所做的。

    【讨论】:

    • 查看我的编辑!:) 我认为我的问题更清楚了:)
    • @DanielGustafsson:我认为您发布的内容不太正确。这不是有效的 JSON 或 JSONP。它看起来像开发工具的文本输出,也许?
    • 是的,它来自 chrome devtool。这与我在 ajax 帖子中取得的成功不一样吗? @戴夫沃德?
    • @DanielGustafsson:它是相同数据结构的表示,但不是 JSON。由于这表明您已经有了一个对象,因此无需解析它。它可以按原样使用。
    【解决方案4】:

    希望这能解决您的问题:

    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);
      }
    });
    

    实际上,JSONP 根本不是 JSON,它只是 JavaScript 代码。在这种情况下没有理由进行 eval ......你可以在全局定义该函数后简单地做。 jquery 还提供了使用特定 jsonp 回调发出同域 jsonp 请求的方法,如果您必须使用 jQuery 来执行

    // 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);
      }
    });
    

    【讨论】:

    • 如果您使用 jquery,则不需要定义函数,jquery 会为您执行此操作(这样做可能会导致 jquery 抛出错误)。你只是把事情复杂化了。
    • JSON.parse("[object Object]");你说的是 json 对象中的类型转换,我可以用它来解析 json,但是当我弄乱 jsonp 时,它只是一个 js 代码,我需要先将它转换成 json,然后我才能解析它。尽管如此,我们也可以使用 jquery 方法 window.alert(JSON.stringify(result));
    • 所以没有好的方法可以将 header-info 与每个数组@KevinB 和@phpBud 中的数据配对?所以我要做的是通过查看所有数组并找到我想要的数据来制作我自己的对象?像 val.resultSets[4].rowSet[1]
    • 您可以按照您认为合适的方式构建数据。我不明白你在问什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多