3

I have wasted two days on this and I can't take it anymore. I am getting well formed JSON data from my $.ajax call. Sample below...

"results":[
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}"
]

I have attempted to access the values in this single array of JSON objects and just can't figure it out. Here's my code below...

success:function (data) {

/*
$.each(data.results, function(i, val) {
console.log(i, val);
});
*/

$('a.previewUrl').each(function (i) {
    var res = jQuery.parseJSON(data.results[0]);
    var previewUrl = $(this);
if(previewUrl.attr("href") == '') {
    previewUrl.attr("href", res[i].d);
}

});

} // end success

The console.log iteration over each JSON object in the array prints out fine but I think I have tried a dozen different ways to grab these values in the $.each() loop. What I am missing?

3
  • That doesn't look like well-formed JSON? What's with all the extra quotes? Commented Jun 6, 2012 at 18:05
  • 1
    Hmmm... Shouldn't data.results[0] be data.results[i], and res[i] to res? Since you are iterating over an array of strings? Also, your json strings looks a bit odd, your quotes aren't escaped. And, why do you have json strings, inside of a json string? Commented Jun 6, 2012 at 18:05
  • OMG. Kevin B is right. Two days of looking at this code and I didn't even notice they were JSON strings inside of another JSON string. Thank you, Kevin B. Commented Jun 6, 2012 at 18:17

1 Answer 1

2

Your Json isn't valid. Try putting it through jsonlint and see what happens.

I think this could be what you were aiming for:

{
"results": [
    {
        "a": "data",
        "b": "data",
        "c": "data"
    },
    {
        "a": "data",
        "b": "data",
        "c": "data"
    },
    {
        "a": "data",
        "b": "data",
        "c": "data"
    },
    {
        "a": "data",
        "b": "data",
        "c": "data"
    }
]}

and if you're using jQuery's $.getJSON function, you don't need to parse your data or if you're using the $.ajax function, set the datatype to json so it wil parse the data for you.

Sign up to request clarification or add additional context in comments.

Comments

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.