sample-jspsych-psiturk-experiment/jspsych.js at master · jspsych/sample-jspsych-psiturk-experiment
Wed Jun 02 2021 17:02:33 GMT+0000 (Coordinated Universal Time)
Saved by @Kara_schwartz29 ##jspsych ##javascript ##psiturk
jsPsych.dataAPI = (function() { var module = {}; // core.dataAsCSV returns a CSV string that contains all of the data // append_data is an option map object that will append values // to every row. for example, if append_data = {"subject": 4}, // then a column called subject will be added to the data and // it will always have the value 4. module.dataAsCSV = function(append_data) { var dataObj = jsPsych.data(); return JSON2CSV(flattenData(dataObj, append_data)); }; module.localSave = function(filename, format, append_data) { var data_string; if(format == 'JSON' || format == 'json') { data_string = JSON.stringify(flattenData(jsPsych.data(), append_data)); } else if(format == 'CSV' || format == 'csv') { data_string = module.dataAsCSV(append_data); } else { throw new Error('invalid format specified for jsPsych.dataAPI.localSave'); } saveTextToFile(data_string, filename); }; module.getTrialsOfType = function(trial_type){ var data = jsPsych.data(); data = flatten(data); var trials = []; for(var i = 0; i < data.length; i++){ if(data[i].trial_type == trial_type){ trials.push(data[i]); } } return trials; }; module.displayData = function(format) { format = (typeof format === 'undefined') ? "json" : format.toLowerCase(); if(format != "json" && format != "csv") { console.log('Invalid format declared for displayData function. Using json as default.'); format = "json"; } var data_string; if(format == 'json') { data_string = JSON.stringify(flattenData(jsPsych.data()), undefined, 1); } else { data_string = module.dataAsCSV(); } var display_element = jsPsych.getDisplayElement(); display_element.append($('<pre>', { html: data_string })); } // private function to save text file on local drive function saveTextToFile(textstr, filename) { var blobToSave = new Blob([textstr], { type: 'text/plain' }); var blobURL = ""; if (typeof window.webkitURL !== 'undefined') { blobURL = window.webkitURL.createObjectURL(blobToSave); } else { blobURL = window.URL.createObjectURL(blobToSave); } var display_element = jsPsych.getDisplayElement(); display_element.append($('<a>', { id: 'jspsych-download-as-text-link', href: blobURL, css: { display: 'none' }, download: filename, html: 'download file' })); $('#jspsych-download-as-text-link')[0].click(); } // // A few helper functions to handle data format conversion // function flattenData(data_object, append_data) { append_data = (typeof append_data === undefined) ? {} : append_data; var trials = []; // loop through data_object for (var i = 0; i < data_object.length; i++) { for (var j = 0; j < data_object[i].length; j++) { var data = $.extend({}, data_object[i][j], append_data); trials.push(data); } } return trials; }
Comments