Home > Software design >  I need to validate data is in JSON format in python
I need to validate data is in JSON format in python

Time:11-02

I'm making a program that needs to validate that certain data is in json format. What's in the json does not mater and will change each time a user runs the program. Could anyone provide examples of ways to validate that data is in a json format?

Currently attempting to use the jsonschema library.

CodePudding user response:

Use json.loads

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.

CodePudding user response:

>> f = open("data.json")

>> load_f = json.load(f)

>> isinstance(load_f, dict)

>> True

CodePudding user response:

import json

valid_json_example: str = '{"example":"json_format"}'
invalid_json_example: str = '{"example":json_format}'

try:
    # change json.loads(valid_json_example) to json.loads(invalid_json_example)
    # this will raise JSONDecodeError exception
    result: dict = json.loads(valid_json_example)
    print("valid json")
    
except json.JSONDecodeError:
    print("invalid json")
  • Related