Serialize objects to JSON

Can I save an object in my workspace across sessions by serializing it to JSON? If possible, how can I do it? And what limitations should I be aware of?

Dear Kim,
There are many ways of doing this. Attached code and wsp will take an object and create a json that can be stored to file. Then we can read the file and re-create the data object from the json.

I hope it inspires to do something similar. There are of course a bit of error handling to fix, and take care of missing values etc.

// data object
object mydata {
	string 	name;
	date 	signup;
	number	age;
	logical	active;
};

//global variable to fill with data
vector(mydata) glob_data;

//dummy data
vector(string) names = ['Joe', 'Jenna', 'Jimbo'];
vector(date) signups = today() - [10,22,33];
vector(number) ages = [34,31,22];
vector(logical) status = [true, true, false];

// fill vector of object with dummy data
out void init_data(){
	resize(glob_data,0);

	for(integer i = 0; i< v_size(names) ;i++){
		mydata tmp = new mydata;
		tmp.name = names[i];
		tmp.signup = signups[i];
		tmp.age = ages[i];
		tmp.active = status[i];

		push_back(glob_data, tmp);
	}
}

// we have object data. serialize to json and write to file.
out string serialize_me(){
		json.builder jb = new json.builder(2);
		jb.append(glob_data);
		
		string ret = jb.get();
		file_write('z:/tmp/mydata.json', ret);
		
		return ret;
}

//we have a file with json. parse and fill object with data.
out vector(string) read_data(){
	string tmp = file_read('z:/tmp/mydata.json');
	json.node js = json.parse(tmp);
	vector(string) ret;
	vector(string) err;
	integer n = js.get_array_size();
	for(integer i = 0; i<n;i++){
		mydata m = new mydata;
		json.get_object(js.get_array_element(i), m, err);
		push_back(ret, strcat([m.name,' | ',string(m.age),' | ', string(m.signup),' | ', string(m.active)]));
	}
	return ret;	
}

simple_json_serializer.qlw (7.7 KB)