Created
January 21, 2012 18:39
-
-
Save kisom/1653544 to your computer and use it in GitHub Desktop.
validate json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# author: kyle isom <[email protected]> | |
# license: isc / public domain dual-license | |
# | |
# i have this saved to ~/bin/validjson | |
""" | |
Quickly check whether a JSON file is valid or not. | |
""" | |
import simplejson | |
import sys | |
def valid_json(filename): | |
"""Determine if a file contains valid JSON.""" | |
error = None | |
try: | |
data = open(filename).read() | |
except IOError as io_error: | |
error = str(io_error) | |
else: | |
try: | |
simplejson.loads(data) | |
except simplejson.decoder.JSONDecodeError as json_error: | |
error = str(json_error) | |
return error | |
def check_file(filename): | |
"""Calls valid_json and displays the results.""" | |
error = valid_json(filename) | |
if error: | |
print '%s invalid (%s)' % (filename, error) | |
else: | |
print '%s valid' % (filename, ) | |
def main(filelist): | |
"""Validate a list of filenames.""" | |
for filename in filelist: | |
check_file(filename) | |
if '__main__' == __name__: | |
if not len(sys.argv) > 1: | |
exit(0) | |
else: | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment