Validate JSON using Python

Python has built-in JSON module to work with JSON data. Python is getting popular and becoming the first choice of startup development. JSON is used widely because it easy to understand, compact and built in support in JavaScript.

Validating JSON Using Python.

json.loads() method is used to validate JSON data.

Here is the function which will validate JSON data.

#JSON Validator function
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False

json.loads()

json.loads() loads the JSON data to parse, it will return true or it will fail and raised the exception. This function will work as EAFP (Easier to ask for forgiveness than permission). EAFP is python’s ideology to handle this kind of situation.

Here is the Example of Validating JSON data using Python.

#Validating JSON using Phython Code
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False
    

#Valid JSON Data
""" {
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
"""

#Invalid JSON Data
"""
 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 """


print(json_validator('{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ))#prints True

print (json_validator('{{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}')) #prints Error message and False

#End

These ready-made tools can be used to validate JSON data online JSON Validator on CodeBeautify. and Json Validator.

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");