Skip to content
Advertisement

How to access first element of JSON object array?

I exptect that mandrill_events only contains one object. How do I access its event-property?

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

Advertisement

Answer

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, ‘[‘.

So either correct your source to:

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

and then req.mandrill_events[0], or if you’re stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement