-2

I am using fastjsonschema for validating json records against its schema. Some thing like this:

import fastjsonschema
validate = fastjsonschema.compile({'type': 'string'})
validate('hello')

If the json is valid, it returns the json string else return the error string. I just want to check if the json is valid or not. For this I can do a workaround of comparing output of the validate method and the json input.

But I want something cleaner. May be something like '$?' in unix or something better.

Could you suggest me?

Pradeep
  • 9,667
  • 13
  • 27
  • 34
  • "else return the error string" - no, in case of validation failure it raises `JsonSchemaException` (which is a very clean and correct way to handle it) – Amadan Sep 19 '19 at 05:31
  • Read the docs: `Exception JsonSchemaException is raised from generated funtion when validation fails (data do not follow the definition).` From: https://horejsek.github.io/python-fastjsonschema/index.html#fastjsonschema.compile – rdas Sep 19 '19 at 05:32
  • Thanks @rdas Being a newbie to Python did not gave attention to that. Thanks. – Sumit Bharati Sep 19 '19 at 05:36
  • Thanks @Amadan Being a newbie to Python did not gave attention to that. Thanks. – Sumit Bharati Sep 19 '19 at 05:37
  • `$?` exists because you can't just write `x = validate()` like you can in Python. – chepner Sep 19 '19 at 14:21

1 Answers1

0

From the documentation, there seem to be two different exceptions thrown in case of error:

In Python, you can simply wrap that with a try ... except block like this:

try:
    validate = fastjsonschema.compile({'type': 'string'})
    validate(1)
except (fastjsonschema.JsonSchemaException, fastjsonschema.JsonSchemaDefinitionException):
    print("Uh oh ...")
Judge
  • 644
  • 8
  • 11