2

When I make an API request, the API server returns me a JSON object. How do I parse the JSON object to their designated types in Javascript?

This is what is being returned to me:

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

So would like to parse the array, classes, the object, food, and the string student_name, and console log them.

2 Answers 2

1

You need to use JSON.parse() to do it:

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.

display a single element:

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

display all elements of an array:

var arr = myData.classes;

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

For more information:

Sign up to request clarification or add additional context in comments.

4 Comments

sorry but before I accept the answer and upvote, what's the reason for console.dir rather than .log? Also doing console.log(myData.classes) would log it as an array with those strings, correct? But how would I console log the first string, A1, in the classes array? And how would I dynamically console log the strings in the array? Because the size of array is not set.
console.log return strings and console.dir returns objects.
Just use console.log(myData.classess[0]); to get the first element of the classess array
And to get all elements of your array displayed, you should iterate the array. I can write you an example, how to do it
0

JSON is the JavaScript Object Notation, which means JSON snippets already represent JavaScript objects. You just have to parse them using:

var myObject = JSON.parse(json);

And then you can access:

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.