Scanning JSON with JavaScript

Sometimes our code need to handle or process multiple types of objects. Input to our code could be an object of any type and we need to process it by extracting values from it. In java we can use reflection to handle such scenario by scanning the object to find the member variables in it and values in it.  In JavaScript we might came across same scenario, We might have to handle JSON object which could have dynamic fields and we need to know the name of the fields present in the object and what are the corresponding values to process that object. So we need to write a code which could dynamically scan the JSON object and find the name of the fields in it and their values. Below is the sample code how to achieve it with JavaScript.

Example Scenario:
Write a JavaScript function which will make a HTTP call. But additional headers need to be sent while you make HTTP call. And it will be decided by an JSON object passed to your code as argument. JSON object structure will be as below :

{
  "Header-1"  :  "Value-1"
   ...
   ...
  "Header-n" :  "Value-n"
}

Example Code:


  //Find the keys or name of the fields present in the JSON Object
  var keys = Object.keys(jsonObj);

  //Find the value in the object for each key or field name
  for(var i=0; i<keys.length; i++){
    var key = keys[i];
    var val = jsonObj[key];
    console.log("Key: " + key +", Value: " + val);
  }


Example JSON:
var jsonObj = {
  "field1" : "value1",
  "field2" : "value2",
  "field3" : "value3"
}

Example Output :
Key: field1, Value: value1
Key: field2, Value: value2
Key: field3, Value: value3

Happy Programming !!!







No comments:

Post a Comment