开发者

How to clean up dodgy JSON file from server

I'm trying to use a JSON feed from our site, which unfortately is not formated correctly. I can clean up the feed via calling it first via the $.ajax call, but want to be able to pass this cleaned up content back to iterate over as if it was a JSON object.

$(document).ready(function()
{
    // use ajax call as json supplied needs cleaning first
    $.ajax({
        url: 'JSON.txt',
        success: function (data)
        {
            var i = 0;
            va开发者_运维技巧r html = '';
            var regex = /<!--.+?-->/g;
            responseText = data.replace(regex,'');  // clean up Jahia's dodgy JSON output
            $('body').append(responseText);
        }
    });
});

Any ideas how to return the responseText back as a JSON object so that I can use the $.each function to parse the file?


Since you're already using jquery, use jQuery.parseJSON() to convert the string to a JSON object.


You can use the json library to convert a text string to a json object.

Library: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Documentation: http://www.json.org/js.html


You can't really return anything from the body of most AJAX callback functions because they're asynchronous. Once you've formatted the JSON String you can turn it into a JSON Object by eval'ing it (technically bad practice, but it's how you can turn a string into an object), and then passing it to another function as a parameter. So something like this:

var newJSON = eval(responseText);
handleJSON(newJSON);

Where handleJSON would have to be a function you defined elsewhere in the code that knew how to process the responses you'll receive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜