tags:

views:

22

answers:

3

Hi,

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;
            var 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?

A: 

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

Library: http://www.json.org/json2.js

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

Mervyn
Per his description, the JSON Object is not valid as sent back by the Server. He has to modify the string representation before it will parse as an object.
g.d.d.c
Yep, misread the question. I've now removed that chunk of misinformation :)
Mervyn
A: 

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.

g.d.d.c
Thanks for your answers - much appreciated!
Joe
+1  A: 

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

psmears