1BSON_GUIDES(3) libbson BSON_GUIDES(3)
2
3
4
6 bson_reader_t provides a streaming reader which can be initialized with
7 a filedescriptor or memory region. bson_writer_t provides a streaming
8 writer which can be initialized with a memory region. (Streaming BSON
9 to a file descriptor is not yet supported.)
10
11 Reading from a BSON Stream
12 bson_reader_t provides a convenient API to read sequential BSON docu‐
13 ments from a file-descriptor or memory buffer. The bson_reader_read()
14 function will read forward in the underlying stream and return a bson_t
15 that can be inspected and iterated upon.
16
17 #include <stdio.h>
18 #include <bson/bson.h>
19
20 int
21 main (int argc, char *argv[])
22 {
23 bson_reader_t *reader;
24 const bson_t *doc;
25 bson_error_t error;
26 bool eof;
27
28 reader = bson_reader_new_from_file ("mycollection.bson", &error);
29
30 if (!reader) {
31 fprintf (stderr, "Failed to open file.\n");
32 return 1;
33 }
34
35 while ((doc = bson_reader_read (reader, &eof))) {
36 char *str = bson_as_canonical_extended_json (doc, NULL);
37 printf ("%s\n", str);
38 bson_free (str);
39 }
40
41 if (!eof) {
42 fprintf (stderr,
43 "corrupted bson document found at %u\n",
44 (unsigned) bson_reader_tell (reader));
45 }
46
47 bson_reader_destroy (reader);
48
49 return 0;
50 }
51
52 See bson_reader_new_from_fd(), bson_reader_new_from_file(), and
53 bson_reader_new_from_data() for more information.
54
55 Writing a sequence of BSON Documents
56 bson_writer_t provides a convenient API to write a sequence of BSON
57 documents to a memory buffer that can grow with realloc(). The
58 bson_writer_begin() and bson_writer_end() functions will manage the un‐
59 derlying buffer while building the sequence of documents.
60
61 This could also be useful if you want to write to a network packet
62 while serializing the documents from a higher level language, (but do
63 so just after the packets header).
64
65 #include <stdio.h>
66 #include <bson/bson.h>
67 #include <assert.h>
68
69 int
70 main (int argc, char *argv[])
71 {
72 bson_writer_t *writer;
73 bson_t *doc;
74 uint8_t *buf = NULL;
75 size_t buflen = 0;
76 bool r;
77 int i;
78
79 writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
80
81 for (i = 0; i < 10000; i++) {
82 r = bson_writer_begin (writer, &doc);
83 assert (r);
84
85 r = BSON_APPEND_INT32 (doc, "i", i);
86 assert (r);
87
88 bson_writer_end (writer);
89 }
90
91 bson_free (buf);
92
93 return 0;
94 }
95
96 See bson_writer_new() for more information.
97
99 Libbson provides routines for converting to and from the JSON format.
100 In particular, it supports the MongoDB extended JSON format.
101
102 Converting BSON to JSON
103 There are often times where you might want to convert a BSON document
104 to JSON. It is convenient for debugging as well as an interchange for‐
105 mat. To help with this, Libbson contains the functions
106 bson_as_canonical_extended_json() and bson_as_relaxed_extended_json().
107 The canonical format preserves BSON type information for values that
108 may have ambiguous representations in JSON (e.g. numeric types).
109
110 bson_t *b;
111 size_t len;
112 char *str;
113
114 b = BCON_NEW ("a", BCON_INT32 (1));
115
116 str = bson_as_canonical_extended_json (b, &len);
117 printf ("%s\n", str);
118 bson_free (str);
119
120 bson_destroy (b);
121
122 { "a" : { "$numberInt": "1" } }
123
124 The relaxed format prefers JSON primitives for numeric values and may
125 be used if type fidelity is not required.
126
127 bson_t *b;
128 size_t len;
129 char *str;
130
131 b = BCON_NEW ("a", BCON_INT32 (1));
132
133 str = bson_as_relaxed_extended_json (b, &len);
134 printf ("%s\n", str);
135 bson_free (str);
136
137 bson_destroy (b);
138
139 { "a" : 1 }
140
141 Converting JSON to BSON
142 Converting back from JSON is also useful and common enough that we
143 added bson_init_from_json() and bson_new_from_json().
144
145 The following example creates a new bson_t from the JSON string
146 {"a":1}.
147
148 bson_t *b;
149 bson_error_t error;
150
151 b = bson_new_from_json ("{\"a\":1}", -1, &error);
152
153 if (!b) {
154 printf ("Error: %s\n", error.message);
155 } else {
156 bson_destroy (b);
157 }
158
159 Streaming JSON Parsing
160 Libbson provides bson_json_reader_t to allow for parsing a sequence of
161 JSON documents into BSON. The interface is similar to bson_reader_t but
162 expects the input to be in the MongoDB extended JSON format.
163
164 /*
165 * Copyright 2013 MongoDB, Inc.
166 *
167 * Licensed under the Apache License, Version 2.0 (the "License");
168 * you may not use this file except in compliance with the License.
169 * You may obtain a copy of the License at
170 *
171 * http://www.apache.org/licenses/LICENSE-2.0
172 *
173 * Unless required by applicable law or agreed to in writing, software
174 * distributed under the License is distributed on an "AS IS" BASIS,
175 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
176 * See the License for the specific language governing permissions and
177 * limitations under the License.
178 */
179
180
181 /*
182 * This program will print each JSON document contained in the provided files
183 * as a BSON string to STDOUT.
184 */
185
186
187 #include <bson/bson.h>
188 #include <stdlib.h>
189 #include <stdio.h>
190
191
192 int
193 main (int argc, char *argv[])
194 {
195 bson_json_reader_t *reader;
196 bson_error_t error;
197 const char *filename;
198 bson_t doc = BSON_INITIALIZER;
199 int i;
200 int b;
201
202 /*
203 * Print program usage if no arguments are provided.
204 */
205 if (argc == 1) {
206 fprintf (stderr, "usage: %s FILE...\n", argv[0]);
207 return 1;
208 }
209
210 /*
211 * Process command line arguments expecting each to be a filename.
212 */
213 for (i = 1; i < argc; i++) {
214 filename = argv[i];
215
216 /*
217 * Open the filename provided in command line arguments.
218 */
219 if (0 == strcmp (filename, "-")) {
220 reader = bson_json_reader_new_from_fd (STDIN_FILENO, false);
221 } else {
222 if (!(reader = bson_json_reader_new_from_file (filename, &error))) {
223 fprintf (
224 stderr, "Failed to open \"%s\": %s\n", filename, error.message);
225 continue;
226 }
227 }
228
229 /*
230 * Convert each incoming document to BSON and print to stdout.
231 */
232 while ((b = bson_json_reader_read (reader, &doc, &error))) {
233 if (b < 0) {
234 fprintf (stderr, "Error in json parsing:\n%s\n", error.message);
235 abort ();
236 }
237
238 if (fwrite (bson_get_data (&doc), 1, doc.len, stdout) != doc.len) {
239 fprintf (stderr, "Failed to write to stdout, exiting.\n");
240 exit (1);
241 }
242 bson_reinit (&doc);
243 }
244
245 bson_json_reader_destroy (reader);
246 bson_destroy (&doc);
247 }
248
249 return 0;
250 }
251
252 Examples
253 The following example reads BSON documents from stdin and prints them
254 to stdout as JSON.
255
256 /*
257 * Copyright 2013 MongoDB, Inc.
258 *
259 * Licensed under the Apache License, Version 2.0 (the "License");
260 * you may not use this file except in compliance with the License.
261 * You may obtain a copy of the License at
262 *
263 * http://www.apache.org/licenses/LICENSE-2.0
264 *
265 * Unless required by applicable law or agreed to in writing, software
266 * distributed under the License is distributed on an "AS IS" BASIS,
267 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
268 * See the License for the specific language governing permissions and
269 * limitations under the License.
270 */
271
272
273 /*
274 * This program will print each BSON document contained in the provided files
275 * as a JSON string to STDOUT.
276 */
277
278
279 #include <bson/bson.h>
280 #include <stdio.h>
281
282
283 int
284 main (int argc, char *argv[])
285 {
286 bson_reader_t *reader;
287 const bson_t *b;
288 bson_error_t error;
289 const char *filename;
290 char *str;
291 int i;
292
293 /*
294 * Print program usage if no arguments are provided.
295 */
296 if (argc == 1) {
297 fprintf (stderr, "usage: %s [FILE | -]...\nUse - for STDIN.\n", argv[0]);
298 return 1;
299 }
300
301 /*
302 * Process command line arguments expecting each to be a filename.
303 */
304 for (i = 1; i < argc; i++) {
305 filename = argv[i];
306
307 if (strcmp (filename, "-") == 0) {
308 reader = bson_reader_new_from_fd (STDIN_FILENO, false);
309 } else {
310 if (!(reader = bson_reader_new_from_file (filename, &error))) {
311 fprintf (
312 stderr, "Failed to open \"%s\": %s\n", filename, error.message);
313 continue;
314 }
315 }
316
317 /*
318 * Convert each incoming document to JSON and print to stdout.
319 */
320 while ((b = bson_reader_read (reader, NULL))) {
321 str = bson_as_canonical_extended_json (b, NULL);
322 fprintf (stdout, "%s\n", str);
323 bson_free (str);
324 }
325
326 /*
327 * Cleanup after our reader, which closes the file descriptor.
328 */
329 bson_reader_destroy (reader);
330 }
331
332 return 0;
333 }
334
336 MongoDB, Inc
337
339 2017-present, MongoDB, Inc
340
341
342
343
3441.25.1 Nov 08, 2023 BSON_GUIDES(3)