Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate around a '[' in JSON

Tags:

json

jquery

ajax

I'm new to JSON and moving around in it in jQuery. I'm fine until I hit a '[', as in:

  "gd$when": [{
    "startTime": "2006-11-15",
    "endTime": "2006-11-17",
    "gd$reminder": [{"minutes": "10"}]
  }],

I tried to do a

eventTime = event["gd$when"]["startTime"];

to get to the 'startTime' (Yes, event is the variable for ajax stuff, it's all working fine until I hit the '[')

Thanks for any help.

like image 748
Kyle Hotchkiss Avatar asked Dec 22 '22 03:12

Kyle Hotchkiss


2 Answers

[ ] is an array. try event["gd$when"][0]["startTime"];

like image 78
Timothy Avatar answered Jan 09 '23 10:01

Timothy


eventTime = event.gd$when[0].startTime looks more correct.

It is not a JSON question, but a JavasSript question. In JavaScript

var t = ['one','next','last'];

defines an array from three items which can be accessed by construct t[0], t[1], t[2].

var x = {
    "startTime": "2006-11-15",
    "endTime": "2006-11-17",
    "gd$reminder": [{"minutes": "10"}]
  };

defines object x with properties startTime, endTime and gd$reminder. One can don't use "" for the name of properties if they can no special characters. To access the value of properties one use either index conversion x["startTime"] or dot conversion x.startTime. The way x.startTime is better and is recommended.

So the answer on your question is

eventTime = event.gd$when[0].startTime
like image 37
Oleg Avatar answered Jan 09 '23 10:01

Oleg