# Serialize objects to JSON

**URL:** <https://quantlab.discourse.group/t/serialize-objects-to-json/65>\
**Category:** Qlang Language\
**Tags:** json, serialize\
**Created:** [May 8, 2024, 9:17am UTC](https://quantlab.discourse.group/t/serialize-objects-to-json/65 "2024-05-08T09:17:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kim](https://avatars.discourse-cdn.com/v4/letter/k/9f8e36/32.png) [@kim](https://quantlab.discourse.group/u/kim)\
**Post date:** [May 8, 2024, 9:17am UTC](https://quantlab.discourse.group/t/serialize-objects-to-json/65/1 "2024-05-08T09:17:06Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![QuantBob](https://yyz1.discourse-cdn.com/flex003/user_avatar/quantlab.discourse.group/quantbob/32/9_2.png) [@QuantBob](https://quantlab.discourse.group/u/QuantBob)\
**Post date:** [May 29, 2024, 8:14am UTC](https://quantlab.discourse.group/t/serialize-objects-to-json/65/2 "2024-05-29T08:14:20Z")

</div>

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.

```auto
// 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](https://quantlab.discourse.group/uploads/short-url/9B8pGWUeh0v3j7W9juu5wv9TeEr.qlw) (7.7 KB)
