Added JSON output

Also refactored duplicated code into a utility class.