2

I am trying to loop through a JSON string that I have gotten from PHP, the problem I am having is that when I try to loop through my string, it doesn't loop through each object instead it loops through each character in the string.

I thought the solution to this would be to parse it but no success.

var json = JSON.stringify(player.get(url));
console.log(json);
json = $.parseJSON(json);

for (var key in json) {
    if (json.hasOwnProperty(key)) {
        console.log(key + " -> " + json[key]);
    }
}

I am getting a perfectly good JSON result, because I have tested it in an online converter -

{
    "id": "1",
    "username": "Jessica",
    "password": "password",
    "age": "100",
    "size": "100"
}

However through when I loop through it, the console displays this:

0 -> { index.html:29

1 -> " index.html:29

2 -> 0 index.html:29

3 -> " index.html:29

4 -> : index.html:29

5 -> " index.html:29

6 -> 1 index.html:29

7 -> " index.html:29

8 -> , index.html:29

9 -> " index.html:29

10 -> c index.html:29

11 -> h index.html:29

12 -> a index.html:29

13 -> r

Any ideas to why it's not looping through the json object properly?

  • I am suggesting to loop using `$.each`. Take a look on those two relevant questions on how to loop through a json object. 1. [how to loop through json array in jquery?](http://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery) 2. [jQuery loop over JSON result from AJAX Success?](http://stackoverflow.com/questions/733314/jquery-loop-over-json-result-from-ajax-success) – Athafoud Aug 10 '14 at 22:41
  • You're getting that result because it's still a string, not an object. – adeneo Aug 10 '14 at 22:41

1 Answers1

3

Change

var json = JSON.stringify(player.get(url));

to

var json = player.get(url);

If player.get(url); returns a string containing JSON, there is no need to convert that string to JSON as well.

You are basically converting the data to JSON twice, but only parsing it once. So either, parse the data twice or do the more reasonable thing and don't convert a string containing JSON to JSON.

scrowler
  • 24,273
  • 9
  • 60
  • 92
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143