Libbson은 JSON 형식으로 변환하거나 JSON 형식에서 변환하기 위한 루틴을 제공합니다. 특히 MongoDB 확장 JSON 형식을 지원합니다.
BSON을 JSON으로 변환
BSON 문서 JSON 으로 변환해야 하는 경우가 종종 있습니다. 디버깅 및 교환 형식에 편리합니다. 이를 돕기 위해 Libbson에는 bson_as_canonical_extended_json 및 bson_as_relaxed_extended_json 함수가 포함되어 있습니다. 표준 형식은 JSON 에서 모호한 표현이 있을 수 있는 값(예: 숫자 유형)에 대해 BSON 유형 정보를 보존합니다.
bson_t *b; size_t len; char *str; b = BCON_NEW ("a", BCON_INT32 (1)); str = bson_as_canonical_extended_json (b, &len); printf ("%s\n", str); bson_free (str); bson_destroy (b);
{ "a" : { "$numberInt": "1" } }
완화된 형식은 숫자 값에 JSON 기본 형식을 선호하며 유형 충실도가 필요하지 않은 경우 사용할 수 있습니다.
bson_t *b; size_t len; char *str; b = BCON_NEW ("a", BCON_INT32 (1)); str = bson_as_relaxed_extended_json (b, &len); printf ("%s\n", str); bson_free (str); bson_destroy (b);
{ "a" : 1 }
JSON을 BSON으로 변환
JSON 에서 다시 변환하는 것도 유용하고 일반적으로 bson_init_from_json 및 bson_new_from_json을 추가했습니다.
다음 예시 JSON 문자열 에서 새 bson_t를 {"a":1}
생성합니다.
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); }
스트리밍 JSON 구문 분석
Libbson은 JSON 문서 시퀀스를 BSON 으로 구문 분석할 수 있도록 bson_json_reader_t를 제공합니다. 인터페이스는 bson_reader_t와 유사하지만 입력이 MongoDB 확장 JSON 형식이어야 합니다.
/* * Copyright 2009-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This program will print each JSON document contained in the provided files * as a BSON string to STDOUT. */ int main (int argc, char *argv[]) { bson_json_reader_t *reader; bson_error_t error; const char *filename; bson_t doc = BSON_INITIALIZER; int i; int b; /* * Print program usage if no arguments are provided. */ if (argc == 1) { fprintf (stderr, "usage: %s FILE...\n", argv[0]); return 1; } /* * Process command line arguments expecting each to be a filename. */ for (i = 1; i < argc; i++) { filename = argv[i]; /* * Open the filename provided in command line arguments. */ if (0 == strcmp (filename, "-")) { reader = bson_json_reader_new_from_fd (STDIN_FILENO, false); } else { if (!(reader = bson_json_reader_new_from_file (filename, &error))) { fprintf ( stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } } /* * Convert each incoming document to BSON and print to stdout. */ while ((b = bson_json_reader_read (reader, &doc, &error))) { if (b < 0) { fprintf (stderr, "Error in json parsing:\n%s\n", error.message); abort (); } if (fwrite (bson_get_data (&doc), 1, doc.len, stdout) != doc.len) { fprintf (stderr, "Failed to write to stdout, exiting.\n"); exit (1); } bson_reinit (&doc); } bson_json_reader_destroy (reader); bson_destroy (&doc); } return 0; }
예시
다음 예시 에서는 stdin
에서 BSON 문서를 읽고 이를 stdout
에 JSON 으로 출력합니다.
/* * Copyright 2009-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This program will print each BSON document contained in the provided files * as a JSON string to STDOUT. */ int main (int argc, char *argv[]) { bson_reader_t *reader; const bson_t *b; bson_error_t error; const char *filename; char *str; int i; /* * Print program usage if no arguments are provided. */ if (argc == 1) { fprintf (stderr, "usage: %s [FILE | -]...\nUse - for STDIN.\n", argv[0]); return 1; } /* * Process command line arguments expecting each to be a filename. */ for (i = 1; i < argc; i++) { filename = argv[i]; if (strcmp (filename, "-") == 0) { reader = bson_reader_new_from_fd (STDIN_FILENO, false); } else { if (!(reader = bson_reader_new_from_file (filename, &error))) { fprintf ( stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } } /* * Convert each incoming document to JSON and print to stdout. */ while ((b = bson_reader_read (reader, NULL))) { str = bson_as_canonical_extended_json (b, NULL); fprintf (stdout, "%s\n", str); bson_free (str); } /* * Cleanup after our reader, which closes the file descriptor. */ bson_reader_destroy (reader); } return 0; }