PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to check JSON format validation?

 July 23, 2022     json, python     No comments   

Issue

My program gets a JSON file that has an information for service.
Before run the service program, I want to check if the JSON file is valide(Only check whether all necessary keys exist).
Below is the standard(necessary datas) JSON format for this program:

{
    "service" : "Some Service Name"
    "customer" : {
        "lastName" : "Kim",
        "firstName" : "Bingbong",
        "age" : "99",
    }
}

Now I am checking the JSON file validation like this:

import json

def is_valid(json_file):

    json_data = json.load(open('data.json'))

    if json_data.get('service') == None:
        return False
    if json_data.get('customer').get('lastName') == None:
        return False
    if json_data.get('customer').get('firstName') == None:
        return False
    if json_data.get('customer').get('age') == None:
        return False

    return True

Actually, the JSON standard format has more than 20 keys. Is there any other way to check the JSON format?


Solution

You might consider jsonschema to validate your JSON. Here is a program that validates your example. To extend this to your "20 keys", add the key names to the "required" list.

import jsonschema
import json

schema = {
    "type": "object",
    "properties": {
        "customer": {
            "type": "object",
            "required": ["lastName", "firstName", "age"]}},
    "required": ["service", "customer"]
}

json_document = '''{
    "service" : "Some Service Name",
    "customer" : {
        "lastName" : "Kim",
        "firstName" : "Bingbong",
        "age" : "99"
    }
}'''

try:
    # Read in the JSON document
    datum = json.loads(json_document)
    # And validate the result
    jsonschema.validate(datum, schema)
except jsonschema.exceptions.ValidationError as e:
    print("well-formed but invalid JSON:", e)
except json.decoder.JSONDecodeError as e:
    print("poorly-formed text, not JSON:", e)

Resources:

  • https://pypi.python.org/pypi/jsonschema
  • http://json-schema.org/example1.html


Answered By - Robᵩ
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing