使用jsonlib解析错误

时间:2011-06-05 13:07:39

标签: javascript json parsing goo.gl

我正在使用goo.gl API和Javascript使用jsonlib这样做:

function googl(url, cb) {
    jsonlib.fetch({
        url: 'https://www.googleapis.com/urlshortener/v1/url?key=<my-api-key>',
        header: 'Content-Type: application/json',
        data: JSON.stringify({longUrl: url})
    }, function (m) {
        var result = null;
        try {
            result = JSON.parse(m.content).id;
            if (typeof result != 'string') {
                result = null;
            }
        } catch (e) {
            result = null;
        }
        cb(result);
    });
}

但是当我尝试运行它时,我收到了这个错误:

  

ReferenceError:找不到变量:jsonlib_cb_1307278663586 - fetch:1

fetch:1的内容:

jsonlib_cb_1307278663587({"url": "https://www.googleapis.com/urlshortener/v1/url?key=<my-api-key>", "headers": {"via": "HTTP/1.1 GWA", "x-content-type-options": "nosniff", "x-google-cache-control": "remote-fetch", "expires": "Fri, 01 Jan 1990 00:00:00 GMT", "server": "GSE", "x-xss-protection": "1; mode=block", "etag": "\"0CNIIHrQYpIA69r1Pk9QCe1kzwI/u2pHqKdqG-dNhbJgEDlvIXi9lWk\"", "pragma": "no-cache", "cache-control": "no-cache, no-store, max-age=0, must-revalidate", "date": "Sun, 05 Jun 2011 13:14:52 GMT", "x-frame-options": "SAMEORIGIN", "content-type": "application/json; charset=UTF-8"}, "original-encoding": "iso-8859-1", "content": "{\n \"kind\": \"urlshortener#url\",\n \"id\": \"http://goo.gl/45cs\",\n \"longUrl\": \"http://developer.android.com/guide/practices/ui_guidelines/icon_design.html\"\n}\n"})

我需要做些什么来纠正这个问题?

PS:我已从代码中删除了我的API密钥以使其公开,在我的测试中,API密钥就在那里并且它是正确的,因为如果我点击{{我可以看到有效的JSON Safari调试器上的1}}

1 个答案:

答案 0 :(得分:1)

您忘了将代理(在本例中为:jsonlib.com)应该用于POST的方法设置为required by the goo.gl API

查看the documentation of JSONlib,您应该在参数对象method中提供另一个属性,例如:

jsonlib.fetch({
    url: 'https://www.googleapis.com/urlshortener/v1/url',
    header: 'Content-Type: application/json',
    method: 'POST',
    data: JSON.stringify({longUrl: url})
}, function (m) {
    /* … */
});

现在m.content包含

'{ "kind": "urlshortener#url", "id": "http://goo.gl/ysEOJ", "longUrl": "http://tobyho.com/Trampolines_in_Javascript_and_the_Quest_for_Fewer_Nested_Callbacks" }'

这是一个完全有效的JSON字符串。