Loading instance variables form a file in Typescript -
here's code:
import fs = require('fs'); export interface answer { order: number, text: string } export class config { responses:answer[]; timestamp_column: string; name_column: string fromjsonfile(filename: string) { var filestring = fs.readfilesync(filename); var parsedfile = json.parse(filestring.tostring()); this.responses = parsedfile.responses; this.timestamp_column = parsedfile.timestamp_column; this.name_column = parsedfile.name_column; } mapanswertonum(answer:string):number { (var of this.responses) { if (a.text == answer) { return a.order;} } throw new error(`invalid response string ${answer}`); } }
it reads in file:
{ "responses": [ { "value": 0, "text": "at loss explain it..."}, { "value": 1, "text": "have vague sense..."}, { "value": 2, "text": "pretty handle on it..."}, { "value": 3, "text": "confident understand it..."}, { "value": 4, "text": "feel pretty expert @ it..."} ], "timestamp_column": "timestamp", "name_column": "first name" }
notice copying each instance variable it's corresponding json field, 1 one, in fromjsonfile. seems repetitive given take care make sure class structured precisely json file. there better way? thanks!
use object.assign
fromjsonfile(filename: string) { var filestring = fs.readfilesync(filename); var parsedfile = json.parse(filestring.tostring()); object.assign(this,parsedfile); }
Comments
Post a Comment