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?

2

1 Answer 1

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.

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

2 Comments

Yeah, just found that out from the last post that was on here, this was the problem
@Felix Thank you so much, amazing!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.