如何分离Json字段并将它们放在变量中

时间:2017-12-14 07:58:49

标签: javascript jquery json

我有一个JSON,我希望将每个字段分开,然后我想分别使用每个字段。

我在下面编写了代码,但它无法正常工作,并在alert中返回undefined。

这是我的代码:

$( document ).ready(function() {
var research=
{
  "city":"1186432",
   "hotelname":"OKHTINSKAYA",
   "indate":"2017-12-23",
   "outedate":"2017-12-30",
   "rooms":[
      {
         "adultcount":"1",
         "childcount":"1,1"
      },
      {
         "adultcount":"1",
         "childcountandage":"0 "
      }
   ]
}
var re = research.rooms.adultcount
alert(re);
});

3 个答案:

答案 0 :(得分:2)

尝试使用以下代码:

var re = research.rooms[0].adultcount

答案 1 :(得分:1)

使用index来使用数组属性research.rooms[0].adultcount

$( document ).ready(function() {
var research=  {
  "city":"1186432",
   "hotelname":"OKHTINSKAYA",
   "indate":"2017-12-23",
   "outedate":"2017-12-30",
   "rooms":[
      {
         "adultcount":"1",
         "childcount":"1,1"
      },
      {
         "adultcount":"1",
         "childcountandage":"0 "
      }
   ]
}
var re = research.rooms[0].adultcount
alert(re);
});

demo https://jsbin.com/zefojozevo/edit?js,console,output

答案 2 :(得分:0)

research.rooms是一个数组,所以为了获得这个数组中每个房间的访问权限 - 你必须循环抛出它。

例如:

research.rooms.map( room => alert(room.adultcount));

或者,在较旧的js语法中:

for(var i = 0; i < research.rooms.length; i++){
    alert(research.rooms[i].adultcount);
}