0

I have a JSON string in this format

{"prey":["{\"distance\": 8.686924173343307, \"signal\": \"-59\", \"frequency\": 2447, \"mac\": \"00:00:00:00:00:00\", \"ip\": \"192.168.43.27\"}"]}

I am parsing this json using var jsonSpy = JSON.parse(userList);

what I am trying to do it get the distance out of it using the code bellow I have two variants both do the same thing. I can get it to output each individual array of distance, signal, frequency, mac and ip but can't get the individual bits of data as shown in the code bellow. I know the loop and the each do the same thing the json prints out a string but when I try to get the distance I get an undefined message not an error it just returns undefined.

for(var i = 0; i < jsonSpy.prey.length; i++)
{
    console.log(jsonSpy.prey[i]);
    console.log(jsonSpy.prey[i].distance);
    ctx.fillRect(jsonSpy.prey[i].distance, 300, 20, 20);
}

$.each(jsonSpy.prey, function(i, item) {
    console.log(jsonSpy.prey[i]);
    console.log(jsonSpy.prey[i].distance);
    ctx.fillRect(jsonSpy.prey[i].distance, 300, 20, 20);
});
7
  • So you want the value of the distance? Commented Apr 17, 2015 at 10:39
  • If it's in that format, you'll need to use JSON.parse(jsonSpy.prey[i]) to read the data. Commented Apr 17, 2015 at 10:40
  • @user4341206 jsonlint.com disagrees and says it is valid Commented Apr 17, 2015 at 10:41
  • Ok so do I need to parse it again inside the loop to get distance @Phylogenesis Commented Apr 17, 2015 at 10:42
  • 1
    Yes, in this instance JSON.parse(jsonSpy.prey[0]).distance will get the value you are after. Commented Apr 17, 2015 at 10:43

1 Answer 1

1

The data inside jsonSpy.prey[0] is still stringified. In order to use the JSON inside, you'll need to run it through JSON.parse() again:

for(var i = 0; i < jsonSpy.prey.length; i++)
{
    var innerJSON = JSON.parse(jsonSpy.prey[i]);

    console.log(jsonSpy.prey[i]);
    console.log(innerJSON.distance);
    ctx.fillRect(innerJSON.distance, 300, 20, 20);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.