Hi Vish,
I've pasted a complete example at the end of this e-mail that works for
me. (It doesn't include any error checking!)
First off, I'm still not sure your structures are appropriately sized --
your example strings require 5 bytes for "name" and 13 bytes for
"example", and they're too long for the structure defined in your code.
For this data, you need at least:
struct data {
char name[5];
char value[13];
struct data*next;
};
Please make sure you understand why the numbers are 5 and 13, not 4 and
12! String overruns are the kind of thing that can break code that
otherwise looks just fine. If you can't guarantee your strings will fit
in the structure, use pointers instead of fixed-length buffers. (Again,
this is a C question, not a jansson question, so you're better off
asking for help on
stackoverflow.com or elsewhere.)
Also, note that "root" is actually an array, not an object, in your JSON
code. That means you should use json_array() and related functions to
construct it.
Also, your code used "json_object_set" to construct "temp". You should
look into Jansson's reference-counting mechanism and make sure you
aren't leaking references (and therefore leaking memory). The code below
uses json_object_set_new() instead. Valgrind is a great tool for
tracking and catching memory leaks.
Finally, you can simplify the contents of your loop by using json_pack()
instead of json_object methods. I'll leave this as an exercise to you.
best,
Graeme
---
#include <jansson.h>
#include <stdio.h>
struct data {
const char name[2];
const char value[6];
struct data *next;
} test_data[] = {
{
.name = "a",
.value = "bcdef",
.next = test_data+1,
}, {
.name = "b",
.value = "cdefg",
.next = NULL,
},
};
int main(void)
{
struct data *var;
json_t *root = json_array();
char *out;
for(var=test_data; var; var=var->next) {
json_t *temp=json_object();
json_object_set_new(temp,"name",json_string(var->name));
json_object_set_new(temp,"value",json_string(var->value));
json_array_append_new(root, temp);
}
out = json_dumps(root, JSON_INDENT(1));
json_decref(root);
puts(out);
free(out);
return(0);
> --
> --
> Jansson users mailing list
>
jansso...@googlegroups.com
>
http://groups.google.com/group/jansson-users
> ---
> You received this message because you are subscribed to the Google
> Groups "Jansson users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to
jansson-user...@googlegroups.com.
> For more options, visit
https://groups.google.com/d/optout.