Skip to content

Get value from JSON object in JavaScript | example code

  • by

First Parse JSON Object in JavaScript With the JSON.parse() Method and then use the key to get value from JSON object in JavaScript. There are two ways to access the properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

Example get value from JSON object in JavaScript

Simple example code gets value from json object in javascript on the console. The format previews the data in a key: value pair and starts and ends with {} (for an object) or [] (for arrays). Keys always tend to be strings and values can be strings and other data types also.

<!DOCTYPE html>
<html>
<head>

  <script>

    var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
    var parsed = JSON.parse(str); // an *array* that contains the user
    var user = parsed[0];         // a simple user

    console.log(user.UserName);   
    console.log(user.Rolename);

  </script>

</head>
</html>

Output:

Get value from JSON object in JavaScript

Code for long data

const json = `{
  "employee": {
    "name": "Roy Mustang",
    "age": 35,
    "favoriteColor": ["Blue", "Black", "Purple"],
    "siblings": {
      "Liza": 20, "Emily": 12
      }
    }
  }`;

var data = JSON.parse(json);

var i;

for(i in data){
  if(data[i]instanceof Object){
    console.log(data[i]);
  }
}

Do comment if you have any doubts or suggestions on this JS JSON topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *