简体   繁体   English

如何访问 JSON 对象数组的第一个元素?

[英]How to access first element of JSON object array?

I exptect that mandrill_events only contains one object.我预计 mandrill_events 只包含一个对象。 How do I access its event-property ?我如何访问它的event-property

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
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.创建任何对象数组( req ),然后简单地执行Object.keys(req)[0]来选择对象数组中的第一个键。

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, '['.要回答您的名义问题,您使用[0]访问第一个元素,但就目前而言, mandrill_events包含一个字符串而不是数组,因此mandrill_events[0]只会为您提供第一个字符 '['。

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:然后req.mandrill_events[0] ,或者如果你坚持它是一个字符串,解析字符串包含的 JSON:

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

the event property seems to be string first you have to parse it to json :事件属性似乎首先是字符串,您必须将其解析为 json :

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

'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. '[{"event":"inbound","ts":1426249238}]'是一个字符串,你不能访问那里的任何属性。 You will have to parse it to an object, with JSON.parse() and then handle it like a normal object您必须使用JSON.parse()将其解析为一个对象,然后像处理普通对象一样处理它

I'll explain this with a general example:我将用一个一般的例子来解释这一点:

var obj = { name: "John", age: 30, city: "New York" };
var result = obj[Object.keys(obj)[0]];

The result variable will have the value "John"结果变量的值为“John”

用 Javascript 解析后,试试这个:

mandrill_events[0].event

Assuming thant the content of mandrill_events is an object (not a string), you can also use shift() function:假设吴丹的内容mandrill_events被物体(未字符串),也可以使用shift()函数:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM