Skip to content

Commit

Permalink
MDL-71685 dataformat_json: include column names in exported file.
Browse files Browse the repository at this point in the history
  • Loading branch information
paulholden committed Aug 9, 2021
1 parent 0d0e66d commit c18987b
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion dataformat/json/classes/writer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace dataformat_json;

defined('MOODLE_INTERNAL') || die();
use core_text;

/**
* JSON data format writer
Expand All @@ -47,6 +47,9 @@ class writer extends \core\dataformat\base {
/** @var $sheetdatadded */
public $sheetdatadded = false;

/** @var string[] $columns */
protected $columns = [];

/**
* Write the start of the file.
*/
Expand All @@ -60,6 +63,10 @@ public function start_output() {
* @param array $columns
*/
public function start_sheet($columns) {
$this->columns = array_map(function($column) {
return core_text::strtolower(clean_param($column, PARAM_ALPHA));
}, $columns);

if ($this->sheetstarted) {
echo ",";
} else {
Expand All @@ -80,6 +87,8 @@ public function write_record($record, $rownum) {
echo ",";
}

// Ensure our record is keyed by column names, rather than numerically.
$record = array_combine($this->columns, (array) $record);
echo json_encode($this->format_record($record), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

$this->sheetdatadded = true;
Expand Down

0 comments on commit c18987b

Please sign in to comment.