0

The similar questions didnt work for me. I have a AJAX GET request. When I show the entire json in the console log it works, but I cant select a single object from it.

My JS

 $.ajax({
        type: "GET",
        url: "http://localhost:8092/api/getdata",
        dataType: "json",

        success: function (data) {

            console.log(data["date"]);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });

This code returns undefined but if I only use console.log(data) it shows everything. Not sure what to do from here.

This is the output when I use console.log(data)

{
   "date": "04-06-2020",
   "id": 4
}

SS when I use console.log(data)

SS when I use console.log(data["id"])

20
  • 1
    What does it show when you just log data ? Commented Jun 4, 2020 at 9:35
  • 1
    Do you get a correct JSON string in data or not? That JSON, if it is a string, then it is missing commas and id::4 should be id:4. This {"date": "04-06-2020", "id": 4} is correct. Without the comma, it is not. Commented Jun 4, 2020 at 9:43
  • 1
    You don't get Unexpected token o if there is no o in your json Commented Jun 4, 2020 at 9:45
  • 2
    ^ well you do, if you have an object and not a string, because then it will convert to [object Object] which has an o in position 1. Commented Jun 4, 2020 at 9:47
  • 4
    >! data is an array with a single object. use data[0]["date"] instead Commented Jun 4, 2020 at 9:56

2 Answers 2

2

It seems you didn't show us the complete output of console.log(data) in your question, there are square brackets ([ ]) missing around it! According to your console screenshot, you get an array, with one object in it.

So the structure is:

[
  {
    "date": "04-06-2020",
    "id": 4
  }
]

Therefore, you need to access the first array element (using [0]) to get the object itself, and from there the property date, like this:

console.log(data[0].date)

(Of course, data[0]["date"] works too, but in my opinion the dot-based property access looks cleaner.)

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

2 Comments

Oh. the array part completely went over my head. Thanks a lot!
Keep in mind that this sort of structure would usually indicate that you may as well receive 0 entries, or 10, not necessarily 1. I don't know what API you use there but check that out, make sure to check data.length too - otherwise you will crash with Cannot read property 'date' of undefined when the length is zero (because data[0] will then be undefined), and you may miss something important when there is more than one item in the list because you look only at the first.
1

data["date"] is used for object which has date attribute. But in your response is an array you need to say data[0]["date"] or data[0].date

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.