0

For some reason my loop is treating this array as a string and looping through each character.

Here's the structure:

var json = [
    {
        "featured": "1",
        "href": "someurl/",
        "property": "some property",
        "location": "<strong>Winston-Salem</strong>North Carolina, United States",
        "date": "23 Oct",
        "year": "2014"
    },
    {
        "featured": "1",
        "href": "someurl/",
        "property": "Sheraton Albuquerque Airport Hotel",
        "location": "<strong>Albuquerque</strong>New Mexico, United States",
        "date": "23 Oct",
        "year": "2014"
     }
    ]

I'm looping it with:

    for(var i = 0; i <= json.length; i++) {
        console.log(json[i]);
    }

Here's a snippet of the type of output I get:

f
e
a 
t 
u 
r 
e 
d 
" 
: 
" 
1
"
3
  • 2
    Probably it is a string. Fetching JSON from a server doesn't magically convert it, you need to call a json library (or eval, if you must). For further diagnosis, what does "typeof(json)" yield? Commented Oct 23, 2014 at 21:24
  • Unrelated to the actual question but the for loop condition should be i < json.length Commented Oct 23, 2014 at 21:25
  • Where is json defined, in a script element or is it data from an ajax response? Commented Oct 23, 2014 at 21:27

1 Answer 1

1

Json is actually a string while you havent serialized it. So it is a string representation of arrays lists and other objects.

If it is an ajax response maybe you have a wrong mime type. So it thinks it is getting a raw string rather than json.

If you are asking such a question I think you probably should read this first JSON

Edit:

If you want to get correct answer you should clarify your question. For example what are you using to get json. If it is jQuery than you shuld use something like this:

$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

took it from here

or if you are using pure js you should manually serialize json like this:

var obj = JSON.parse(text);

took it from here

where text variable contains string got from the server or wherever you get it from.

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

1 Comment

Setting a content-type header won't help. Parsing it with JSON.parse will.

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.