• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

You are here: Home / Python / Validate JSON using Python – with Examples

Validate JSON using Python – with Examples

November 25, 2016 by Jimmy

This article is to 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 of it easy to understand, compact and built-in support in JavaScript.

Validate 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

I am using these ready-made tools to validate JSON data online.

https://codebeautify.org/jsonvalidator
https://jsonformatter.org

Are you also working with JavaScript? try this Validate JSON String Using JavaScript.

Filed Under: Python Tagged With: json, json validator, python, validation

Reader Interactions

Comments

  1. Lalka says

    May 25, 2018 at 8:39 pm

    Loved your JSON Formatter tool.

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in