How to access first element of JSON object array?

前端 未结 6 958
谎友^
谎友^ 2021-01-03 21:10

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

var req = { mandrill_events: \'[{\"event\":\"inboun         


        
6条回答
  •  余生分开走
    2021-01-03 21:58

    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];
    

提交回复
热议问题