How to access the first element of an array of JSON objects?

I highlight that mandrill_events contains only one object. How to access its event-property ?

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' } 
+7
json javascript arrays
source share
5 answers

To answer your cover question, you use [0] to access the first element, but since it costs mandrill_events , it contains a string, not an array, so mandrill_events[0] will just get you the first character, '['.

So, correct your source so that:

 var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] }; 

and then req.mandrill_events[0] , or if you are stuck in the fact that this is a string, parse the JSON containing the string:

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }; var mandrill_events = JSON.parse(req.mandrill_events); var result = mandrill_events[0]; 
+6
source share
 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' } console.log(Object.keys(req)[0]); 

Create any array of objects ( req ), and then just Object.keys(req)[0] select the first key in the Object array.

+6
source share

'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. You will have to parse it into an object using JSON.parse() and then process it like a regular object

+1
source share

the event property seems to be a string, first you have to parse it in json:

  var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }; var event = JSON.parse(req.mandrill_events); var ts = event[0].ts 
+1
source share

After you parse it with Javascript, try the following:

 mandrill_events[0].event 
0
source share

All Articles