Question

I have a moderately complex JSON object, stored as a char *, that I would like to convert to BSON to input it into mongodb using the c "driver" (http://api.mongodb.org/c/0.4/bson.html). While I can use a JSON parser like cJSON to split the object into its elements and add them individualy using commands like bson_append_int( b, "count", 1001 );. I believe the conversion could and should be simpler than that (as there is no loss or gain to the conversion), does anyone know of a better way of doing this?

I think I am looking for something similar to the cpp BSONObj mongo::fromjson ( const string & str ) but I cant find the relavant c function in the docs.

Was it helpful?

Solution

I'm really not that familiar with the C driver but perhaps these two functions might help:

bson_init_from_json
bson_new_from_json

Converting JSON to BSON

bson_t *b;
bson_error_t error;

b = bson_new_from_json ("{\"a\":1}", -1, &error);

if (!b) {
   printf ("Error: %s\n", error.message);
} else {
   bson_destroy (b);
}

http://mongoc.org/libbson/current/json.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top