0

I'm pretty new to JavaScript and I have no idea how to access certain value in JSON string. I had lsit of these objects and I did access them by looping through with $.each function. But it does not seem to work here. I've tried to do alert(data.type); but it gives me undefined variable.

TL;DR:
This is JSON string that I get via AJAX. How can I access type value in JavaScript using jQuery?

{
    "parent_id": "100003381460677",
    "type": "post",
    "title": "a",
    "body": "b",
    "date_normal": "01 May 2012"
}
Stan
  • 25,744
  • 53
  • 164
  • 242
  • 1
    You have to parse the JSON first (explicitly or implicitly, see http://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript). Then you have a JavaScript object which I assume you know know how to work with. – Felix Kling May 01 '12 at 11:32
  • @FelixKling yea, I didn't know that I need to parse it. Thanks, now it works. – Stan May 01 '12 at 11:43

5 Answers5

3

parseJSON helps you

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name );
yital9
  • 6,544
  • 15
  • 41
  • 54
  • Correct one, I was using plugin that did return it as string, not JSON, that's why it went undefined. When I parsed the string to valid JSON it works now. Thanks. – Stan May 01 '12 at 11:32
1

Assuming that this JSON data comes from an AJAX call make sure that you have specified the correct data type (json) if your server is not configured properly to send the correct Content-Type response header:

$.ajax({
    url: '/foo',
    type: 'POST',
    dataType: 'json',
    success: function(result) {
        alert(result.type);
    }
});

Then the argument passed to the success callback will already represent a javascript object (deserialized by jQuery automatically from the server response JSON string). And once you have a javascript object you could directly access its properties by name. In the example you have shown it is a simple object, not an array. So you could directly access the properties by name.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

presuming you use this as your ajax callback:

function(data){ ... }

You can access it with dot notation:

data.type

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76
0

If you are using $.getJSON (this will automatically parse the AJAX response as a JSON object) then

$.getJSON("<url>", function(data, status) {
     $.each(data, function(i, elem) {
          console.log(elem.type);
     });
});

Note that the first argument to the callback in $.each is the index in the array, not the element itself (that's the second argument).

huon
  • 94,605
  • 21
  • 231
  • 225
0

Please take a look at the following two threads;

Find value in Json by javascript

how to get distinct values from json in jquery

I hope it helps.

Community
  • 1
  • 1
mhan
  • 373
  • 3
  • 11