繁体   English   中英

获取 json 数组中的最后一个元素

[英]Get the last element in json array

我怎样才能得到座位 object 中 json 数组中的最后一个元素。我想获得值为 845 的 countryid,但是这个 json 是动态的,所以我想得到座位 object 中的最后一个元素。我的 api 是结构是这样的。 先感谢您。

{
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
        {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
 }

您可以通过按索引访问jsonData.seats数组来做到这一点,最后一项的索引等于jsonData.seats.length-1

简单地:

var countryId = jsonData.seats[jsonData.seats.length-1].countryid

尝试这个:

var jsonObject = {
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
        {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
 }

var lastElement = jsonObject.seats[jsonObject.seats.length-1].countryid

注意:@iuliu.net 代码的副本

使用 DOT

example.at(-1)

 var jsonObject = {
        "expirationDate":"April 21, 2017",
        "remainingDays":325,
        "seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
                {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
                 }

var lastElement = jsonObject.seats.at(-1).countryid

我使用了上面的建议,并在 GSON lib 的循环 JsonElement 对象中使用了它。 以防万一有人在寻找我所做的相同的事情。

         for (JsonElement obj : entries){
             
           //Do your stuff
            
           if (entries.get(entries.size() - 1).equals(obj)){
              //Do stuff if your in last position of the jsonarray array
           }else{
              //Do stuff until you reach the last position
           }
           
         }

您可以反转数组,然后获取第一个元素: el.reverse()[0]

对于您的示例:

 var jsonObject = { "expirationDate": "April 21, 2017", "remainingDays": 325, "seats": [ {"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840}, {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}, ] } console.log( jsonObject.seats.reverse()[0].countryid ); //845

对于希望在 JSONPath 语法中执行此操作的任何人,您可以使用$.seats[-1:]执行此操作。 如果你想做一些事情,比如让countryid属性嵌套在最后一个元素中,那就是$.seats[-1:][countryid]

这对于在 API 客户端中测试端点时链接请求很方便。

暂无
暂无

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

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