How to access first element of JSON object array?

前端 未结 6 914
谎友^
谎友^ 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:52

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

     var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
     var event = JSON.parse(req.mandrill_events);
     var ts =  event[0].ts
    
    0 讨论(0)
  • 2021-01-03 21:52

    After you parse it with Javascript, try this:

    mandrill_events[0].event
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2021-01-03 22:02
    var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
    
    console.log(Object.keys(req)[0]);
    

    Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.

    0 讨论(0)
  • 2021-01-03 22:03

    Assuming thant the content of mandrill_events is an object (not a string), you can also use shift() function:

    var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
    var event-property = req.mandrill_events.shift().event;
    
    0 讨论(0)
  • 2021-01-03 22:05

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

    0 讨论(0)
提交回复
热议问题