I have an array
arr1[4][4], arr2[4][4];I want to write to json file like this{"arr1":[{"a":1,2,3,4},
Mufti-dimensional arrays in C are quite tricky, so see how I deal with
passing them into the helper function and get at the elements inside.
If you're in C++ the STL classes make this much easier.
More specific to Jansson is to use caution with reference counting.
Notice than I'm mostly using Jansson functions that steal references
so I don't have to explicitly "delete" many of my intermediate values.
Read the Jansson documentation on this issue.
==== C Code ====
#include <stdio.h>
#include <jansson.h>
void add_2array_to_json( json_t* obj, const char* name, const int*
marr, size_t dim1, size_t dim2 )
{
size_t i, j;
json_t* jarr1 = json_array();
for( i=0; i<dim1; ++i ) {
json_t* jarr2 = json_array();
for( j=0; j<dim2; ++j ) {
int val = marr[ i*dim2 + j ];
json_t* jval = json_integer( val );
json_array_append_new( jarr2, jval );
}
json_array_append_new( jarr1, jarr2 );
}
json_object_set_new( obj, name, jarr1 );
return;
}
int main()
{
json_t* jdata;
char* s;
int arr1[2][3] = { {1,2,3}, {4,5,6} };
int arr2[4][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} };
jdata = json_object();
add_2array_to_json( jdata, "arr1", &arr1[0][0], 2, 3 );
add_2array_to_json( jdata, "arr2", &arr2[0][0], 4, 4 );
s = json_dumps( jdata, 0 );
puts( s );
free( s );
json_decref( jdata );
return 0;
}
===== END CODE =====
When run it outputs:
{"arr1": [[1, 2, 3], [4, 5, 6]], "arr2": [[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]}
--
Deron Meranda
http://deron.meranda.us/