3

I'm currently trying to insert a JSON file into my mongoDB. I've already seen that this was solved by making use of the mongo::BSONObj in the past... But this doesnt seem to be an option since they released the new mongocxx driver for c++11. This is what I found in the bsoncxx src files:

BSONCXX_API document::value BSONCXX_CALL from_json(stdx::string_view json);
/// Constructs a new document::value from the provided JSON text
///
/// @param 'json'
///  A string_view into a JSON document
///
/// @returns A document::value if conversion worked.
///
/// @throws bsoncxx::exception with error details if the conversion failed.
///

How do I get my JSON file into a stdx::string_view?

Thanks!

acm
  • 12,183
  • 5
  • 39
  • 68
cylex
  • 45
  • 1
  • 6

1 Answers1

6

A bsoncxx::stdx::string_view can be constructed from a std::string. Simply load your file contents (assuming it contains a single JSON object) into a std::string (perhaps via std::ifstream), and pass that std::string to bsoncxx::from_json. The object returned from bsoncxx::from_json is a bsoncxx::document::value, which is a resource-owning type that contains a BSON document.

acm
  • 12,183
  • 5
  • 39
  • 68
  • Thanks for your answer, worked well! is there a way to load in more than just one Object (e.g. arrays and stuff) at a time? – cylex Oct 23 '16 at 12:32
  • The enclosing entity must be an Object, but it can certainly contain nested Arrays and other Object, etc. If you are looking to load multiple JSON documents stored sequentially in a text file into something like a `std::vector` of `bsoncxx::document::value`, then no, we don't have something like that, but it would be straightforward to implement yourself. – acm Oct 24 '16 at 18:01
  • 1
    Do `bsoncxx::document::value bsonObj = bsoncxx::from_json(your_json_string);` – PlsWork Nov 08 '19 at 21:44