Bug hunting - saving & loading json

Hi,

I’d need another pair of eyes. (Or potentially some glasses.)

I can’t spot the error in the code below. Could you please help me?

	// save the content of grid_data; I think it's OK
	json_t* dataToJson() override {
	json_t* rootJ = json_object();
		json_t *notes_json_array = json_array();
		for (int notes_index=0; notes_index<seqLen; notes_index++) {
			json_array_append_new(notes_json_array, json_integer(grid_data[notes_index]));
		}	
		json_object_set(rootJ, "notes", notes_json_array);					
	return rootJ;}

	// load the content of grid_data at startup; it doesn't seem to work 
	void dataFromJson(json_t* rootJ) override {
		json_t *notes_json_array = json_object_get(rootJ, "notes");
		size_t note_index;
		json_t *json_value;
		if (notes_json_array) {
			json_array_foreach(notes_json_array, note_index, json_value) {
				grid_data[note_index] = json_real_value(json_value);
			}
		}
	}

(int) cast?

Your call to json_object_set() leaks memory. Use json_object_set_new() instead.

json_real_value() expects a number with a decimal point. Always use json_number_value() instead to get real values.

What is the type of grid_data[notes_index]? If float, use json_real() to convert to json_t*. If integer, use json_integer_value() to convert to integer.

1 Like

Many thanks for the help! I leave the modified code here for reference but in general the issue was exactly as Andrew pointed out. Another baby-coder-problem solved! ;D

	// json_object_set_new() fixed
	json_t* dataToJson() override {
	json_t* rootJ = json_object();
		json_t *notes_json_array = json_array();
		for (int notes_index=0; notes_index<seqLen; notes_index++) {
			json_array_append_new(notes_json_array, json_integer(grid_data[notes_index]));
		}	
		json_object_set_new(rootJ, "notes", notes_json_array);					
	return rootJ;}

	// json_integer_value() chosen 
	void dataFromJson(json_t* rootJ) override {
		json_t *notes_json_array = json_object_get(rootJ, "notes");
		size_t note_index;
		json_t *json_value;
		if (notes_json_array) {
			json_array_foreach(notes_json_array, note_index, json_value) {
				grid_data[note_index] = json_integer_value(json_value);
			}
		}
	}
1 Like

My next push will have the _new.