接近JSON数据返回'undefined'

时间:2019-04-12 13:30:22

标签: node.js json express axios

当我访问“ dept_name”时,JSON返回“ undefined”。 如何返回正确的输出?

API中的JSON对象(内容)

"departments": [
      {
        "dept_no": "d005",
        "dept_name": "Development",
        "from_date": "1994-07-03",
        "to_date": "9999-01-01",
        "dept_manager": [
          {
            "emp_no": 110511,
            "first_name": "DeForest",
            "last_name": "Hagimont",
            "email": "110511@cloud-spartan.com",
            "from_date": "1985-01-01",
            "to_date": "1992-04-25"
          },
          {
            "emp_no": 110567,
            "first_name": "Leon",
            "last_name": "DasSarma",
            "email": "110567@cloud-spartan.com",
            "from_date": "1992-04-25",
            "to_date": "9999-01-01"
          }
        ]
      }
    ],

当我访问数据['部门'] .dept_no返回'未定义'

      var content_depart = content['departments'];
      console.log(content_depart);
      var department = content_depart.dept_name;
      console.log(department);

console.log(content_depart)

[ { dept_no: 'd005',
    dept_name: 'Development',
    from_date: '1994-07-03',
    to_date: '9999-01-01',
    dept_manager: [ [Object], [Object] ] } ]

console.log(部门)

undefined

3 个答案:

答案 0 :(得分:0)

在访问数据之前添加索引

      var department = content_depart[0].dept_name;
      console.log(department);

答案 1 :(得分:0)

data['departments']是一个数组

let data =
{ //               v--------- array !
    "departments": [
    { // ...

您不能直接访问其成员,但必须先指定索引。例如:

let data = {"departments":[{"dept_no":"d005","dept_name":"Development","from_date":"1994-07-03","to_date":"9999-01-01","dept_manager":[{"emp_no":110511,"first_name":"DeForest","last_name":"Hagimont","email":"110511@cloud-spartan.com","from_date":"1985-01-01","to_date":"1992-04-25"},{"emp_no":110567,"first_name":"Leon","last_name":"DasSarma","email":"110567@cloud-spartan.com","from_date":"1992-04-25","to_date":"9999-01-01"}]}]};
    
console.log(data.departments[0].dept_no);

答案 2 :(得分:0)

$ seq 20 | awk -v h=5 -v r=3 'NR<=h || ((NR-h)%r)==1' 1 2 3 4 5 6 9 12 15 18 是数组而不是对象

因此,请使用content_depart