0

How can I get only "coords" data out of my json object in jquery? And for each object its own coords?

Example of returned json from php as shown in console:

[  
  {  
    "id":"7",
    "name":"EXAMPLE",
    "address":"example adress",
    "coords":"96.0,17.0"
  },
  {  
    same here etc.
  }
]

EDIT: Problem is I can't access json object in a way you all recommended. If I type object[0] I get "[" if I type object[1] I get "{" then I get all the other characters in a sequence '"', "i", "d", etc.

I do my console log in a sucessfull ajax call like so:

.done(function(data) {
    console.log(data[2]);
});

And my php returns data like so:

echo json_encode($myData);
Joe
  • 15,669
  • 4
  • 48
  • 83
LazyPeon
  • 339
  • 1
  • 19

2 Answers2

1

Your data coming back is just a string, so you need to do one of 2 things to get it into JSON format:

  • in your .ajax call, set the option dataType: 'json' alongside the url, data etc parameters ( $.ajax({ url: 'x.php', dataType: 'json' ... }).done(function... )
  • manually parse the JSON in your .done() function ( .done(function(data) { data = $.parseJSON(data); ... }); )

This will convert into it a JSON format, where my original answer below applied.


Since your JSON is an array at the outermost level ([ ]), you can access the first-level items with array notation (eg. [0]). Inside that, you have an object ({ }) so you need dot-notation from there (eg. [0].coords).

Assuming your variable is called myJson you can get at the first coords with myJson[0].coords, the second set with myJson[1].coords, etc. You can loop over myJson to get all coords in a loop.

Joe
  • 15,669
  • 4
  • 48
  • 83
  • I should mention I get this data as a sucessfull ajax call, in my php frunction I write "echo json_encode($vsi_kraji);" and if I do console log in my jquery page I get: "undefined" – LazyPeon Sep 22 '14 at 14:35
  • 1
    @LazyPeon show your AJAX handler. Typically your "success" function for the AJAX call should look something like `success: function(response) {` - in this case, `response` in this example is the `myJson` variable from my answer – Joe Sep 22 '14 at 14:36
  • I updated the question to show what I mean. – LazyPeon Sep 23 '14 at 07:27
  • @LazyPeon answer updated to cover everything you should need :-) – Joe Sep 23 '14 at 08:08
0

You can access coords this way:

objs[0].coords

coords is a member of the first object in the objs array.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175