import json


def convert_format_in_metrics_list(metrics):
  """Converts from human-friendly metadata format to BigQuery friendly format.

  Before:
    'metadata': {'file': 'example.py'}

  After:
    'metadata': [{'key': 'file', 'value': '"example.py"'}]

  Args:
    metrics: A list of metrics dicts.

  Returns:
    A list of metrics dicts with metadata fields reformatted.
  """

  def _convert_metadata_dict(metadatum):
    return [{'key': k, 'value': json.dumps(v)} for (k, v) in metadatum.items()]

  def _handle_special_keys(k, v):
    if k == 'metadata':
      return _convert_metadata_dict(v)
    if k == 'value':
      return json.dumps(v)
    return v

  def _convert_metrics_dict(metric):
    return {k: _handle_special_keys(k, v) for (k, v) in metric.items()}

  return [_convert_metrics_dict(m) for m in metrics]