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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29032525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:39  来源:igfitidea点击:

How to access first element of JSON object array?

javascriptarraysjson

提问by Hedge

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

我预计 mandrill_events 只包含一个对象。我如何访问它event-property

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

采纳答案by stovroz

To answer your titular question, you use [0]to access the first element, but as it stands mandrill_eventscontains 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];

回答by Anuga

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]地选择对象数组中的第一个键。

回答by semirturgay

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

回答by Dimitris Karagiannis

'[{"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

'[{"event":"inbound","ts":1426249238}]'是一个字符串,你不能访问那里的任何属性。您必须将其解析为一个对象,JSON.parse()然后像普通对象一样处理它

回答by Qutayba

After you parse it with Javascript, try this:

用 Javascript 解析后,试试这个:

mandrill_events[0].event

回答by lluisma

Assuming thant the content of mandrill_eventsis 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;