14a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair# Copyright (c) 2015 The Chromium Authors. All rights reserved.
24a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair# Use of this source code is governed by a BSD-style license that can be
34a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair# found in the LICENSE file.
44a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclairimport json
54a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair
64a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclairfrom perf_insights.results import output_formatter
74a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair
84a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair
94a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclairclass JSONOutputFormatter(output_formatter.OutputFormatter):
10cef7893435aa41160dd1255c43cb8498279738ccChris Craik
114a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair  def __init__(self, output_file):
124a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair    # TODO(nduca): Resolve output_file here vs output_stream in base class.
134a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair    super(JSONOutputFormatter, self).__init__(output_file)
144a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair    self.output_file = output_file
154a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair
16cef7893435aa41160dd1255c43cb8498279738ccChris Craik  def Format(self, result_list):
17cef7893435aa41160dd1255c43cb8498279738ccChris Craik    d = [result.AsDict() for result in result_list]
184a4f2fe02baf385f6c24fc98c6e17bf6ac5e0724Dan Sinclair    json.dump(d, self.output_file, indent=2)
1924e1a9362ca2bf7d5cf659231f70375b3761edbaJohn Reck    if hasattr(self.output_file, 'flush'):
20cef7893435aa41160dd1255c43cb8498279738ccChris Craik      self.output_file.flush()
21