How to write JSON file?

1,314 views
Skip to first unread message

Isra Wichakum

unread,
Apr 7, 2012, 4:30:04 AM4/7/12
to jansso...@googlegroups.com
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},
 {"b":1,2,3,4},
 {"c":1,2,3,4},
 {"d":1,2,3,4}
],
 "arr2":[
 {"c":1,2,3,4},
 {"d":1,2,3,4},
 {"e":1,2,3,4},
 {"d":1,2,3,4}
]
}

I want to some example code tutorial

Thanks.

rogerz

unread,
Apr 7, 2012, 4:51:03 AM4/7/12
to jansso...@googlegroups.com
On Sat, Apr 7, 2012 at 4:30 PM, Isra Wichakum <isra...@gmail.com> wrote:
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},
 
It should be 

    "arr1": [
      [1,2,3,4],
      [1,2,3,4],
      [1,2,3,4],
      [1,2,3,4]
    ]
    ...

Deron Meranda

unread,
Apr 7, 2012, 5:40:35 AM4/7/12
to jansso...@googlegroups.com
The following code should be instructive, though I've intentionally
used example data which is more illustrative.

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/

Reply all
Reply to author
Forward
0 new messages