Validate JSON String Using PHP

JSON is the popular data format to transfer data between client and server. There are many JSON validators are available online such as JSON Validator and JSON Validator on CodeBeautify to validate JSON.

As a programmer, I am curious to know how these tools are working. Here I am going to explain.

json_decode() is the function which is been introduce in PHP 5.3 to validate JSON String.

About json_decode

Here is the description is given in PHP specification.

mixed json_decode ( string [, bool = false [, int = 512 [, int = 0 ]]] )

This function takes a JSON encoded the string and converts it into a PHP variable.

Here is the function which works as JSON Validator.

//JSON Validator function
function json_validator($data=NULL) {
	
	if (!empty($data)) {
		
                @json_decode($data);
		
                return (json_last_error() === JSON_ERROR_NONE);
	
        }
	
        return false;
}

Let’s see how does this work.

if (!empty($data))

This condition will check the $data variable is not empty. If $data is empty, then it will return false.

@json_decode($data)

json_decode parses the data and return the PHP variable if the string is valid. If the string is not valid it will generate the error. Character “@” will suppress the error.

return (json_last_error() === JSON_ERROR_NONE);

This will check if $data is valid JSON string by comparing with JSON_ERROR_NONE. json_last_error() return the last error when json_decode() has called if there are any.

Here is the Example of Validating JSON data

<?php
//JSON Validator function
function json_validator($data=NULL) {
	
	if (!empty($data)) {
		
                @json_decode($data);
		
                return (json_last_error() === JSON_ERROR_NONE);
	
        }
	
        return false;
}


//valid JSON Data
/*
 {
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */

$sampleJSONData1 = '{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ; 


//invalid JSON Data
/*
 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */
 

$sampleJSONData2 = '{{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ;

echo (json_validator($sampleJSONData1) ? "JSON is Valid" : "JSON is Not Valid");

echo "
";

echo (json_validator($sampleJSONData2) ? "JSON is Valid" : "JSON is Not Valid");

Accessing instance method of JavaScript using this keyword inside each()

As a Java or C# developer, this keyword can we be used in instance method or in constructor to access variables or instance methods.

JavaScript is a prototype-based scripting language and supports Object-Oriented features and this keyword too.

JQuery is most popular JavaScript Cross-Platform library and 99.99% developers uses it for web development. JQuery has $.each() to iterate jQuery object.

Like

var sum = 0;

var values = [ 10, 20, 30, 40, 50 ];

$.each( values, function(){
sum += this;
});

console.log( sum ); //sum would be 150

In above example, when elements iterate with each, it create dynamic object inside the method named this. Now using this object we can have the access of each element. in this example using this we can get the value.

How this can be used in Javascript class. Here is the example.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    this.getInfo = function() {
         return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 

Now what if we use $.each() in Javascript class and want to use <strong>this </strong>keyword as Javascript class’s instance as well as to get element in the $.each iterator?

function Employee (position,name) {
    this.position = position;
    this.name = name;
    
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){

           //Now what If I want to call getInfo from here   
            this.getInfo(); //Wont Work
            getInfo(); //wont work

          }               
      });
    }
}

var employee = new Employee("Spy","James Bond");
console.log( employee.getInfo() );  // James Bond Spy earns $10,000 
employee.printInfoIfSalary(10000);

When employee.printInfoIfSalary(10000) executed, there is no way using this or with this to call getInfo() method within each method of jQuery and it will throw uncaught TypeError: undefined is not a function.

using this Uncaught TypeError: undefined is not a function

How can we fix this? I have spent more than 1 hour to solve this problem. but finally I figured it out. Here is working code.

Working code to fix above issue.

function Employee (position,name) {
    this.position = position;
    this.name = name;
    //define thisObj as globle variable and give this reference
    //now thisObj can used as this if class instance
    var thisObj = this;
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){
        
          //Now what If I want to call getInfo from here   

          console.log(  thisObj.getInfo() ); //will Work

            //getInfo(); or this.getInfo() //wont work
          }               
      });
    }
}
var employee = new Employee("Spy","James Bond");
console.log(employee.printInfoIfSalary(10000));

In this example we define thisObj = this, reference of this variable to thisObj, and now thisObj can be reference as instance of this class.

I hope this example with help you to understand when jQuery and OOPs concepts needs to use together.

Code for this example:  http://codebeautify.org/htmlviewer/e1ce80

 

 

Welcome to CodeBeautify.org blog

Code Beautify helps you to beautify your code.

Make Your Code Beautiful using CodeBeautify.org

I have developed this site to keep developer as specially UI developer and designer in mind.

CodeBeautify.org will help you to test and save your code that can be share on social platform or at http://stackoverflow.com/ to get help from expert developers.

User can create an account and store code as links. If you want to make public links, Save without login.

Let us know if you want to see a new utility or want to enhance exiting utility.

We are focusing on JSON, XML, JavaScript, HTML, CSS, and Conversion between types of data like XML to JSON , JSON to CSV and many more .

Waiting for your feedback…