如何在Javascript中将JSON对象解析为其指定的类型?

时间:2016-09-27 21:15:04

标签: javascript arrays json parsing react-jsx

当我发出API请求时,API服务器会返回一个JSON对象。如何在Javascript中将JSON对象解析为其指定的类型?

这是归还给我的:

{
    "student_name": "Joshua",
    "classes": [
        "A1",
        "A2",
        "A3",
    ]
    "food": {
        "size": "slice",
        "type": "pepperoni",
    }
}

所以想要解析数组classes,对象,food和字符串student_name,然后控制台记录它们。

2 个答案:

答案 0 :(得分:1)

您需要使用JSON.parse()来执行此操作:

var myData = {
  "student_name": "Joshua",
  "classes": [
      "A1",
      "A2",
      "A3",
  ]
  "food": {
      "size": "slice",
      "type": "pepperoni",
  }
}

var myObject = JSON.parse(myData);

console.log(myObject.student_name); //Output: Joshua 
console.dir(myObject) //to see your object in console.

显示单个元素:

console.log(myData.classes[0]);    

显示数组的所有元素:

var arr = myData.classes;

for(var i in arr) 
{
    console.log(arr[i]);
}

了解更多信息:

答案 1 :(得分:0)

JSON是JavaScript Object Notation,这意味着JSON代码段已经代表JavaScript对象。你只需parse使用:

var myObject = JSON.parse(json);

然后你可以访问:

var myArray = myObject.classes; //should give you an array
console.log(myArray[0]); //should print "A1"

var myFood = myObject.food //should give you a food object with size and type properties
console.log(myFood.size);  //should print "slice"