Uploaded image for project: 'C++ Driver'
  1. C++ Driver
  2. CXX-224

BSONArray jsonString() always prints as object

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • legacy-0.11.0
    • Affects Version/s: legacy-0.0-26compat-2.6.0, legacy-0.8.0
    • Component/s: BSON

      The BSONArray type does not re-implement the jsonString() function, so it defaults to the BSONObj one. This means that arrays are always printed as:

      { "0": 1, "1": "abc"}
      

      rather than using square brackets, etc. We've implemented a custom function, which is here below:

      static std::string arrayJSONString(const mongo::BSONArray& array, mongo::JsonStringFormat format = mongo::Strict, int pretty = 0 ) {
      
          if ( array.isEmpty() ) return "[]";
      
          mongo::StringBuilder s;
          s << "[ ";
          mongo::BSONObjIterator i(array);
          mongo::BSONElement e = i.next();
          if ( !e.eoo() )
              while ( 1 ) {
                  s << e.jsonString( format, false, pretty?pretty+1:0 );
                  e = i.next();
                  if ( e.eoo() )
                      break;
                  s << ",";
                  if ( pretty ) {
                      s << '\n';
                      for( int x = 0; x < pretty; x++ )
                          s << "  ";
                  }
                  else {
                      s << " ";
                  }
              }
          s << " ]";
      
          return s.str();
      }
      

      It's basically identical with a couple of very small changes. I'm happy to submit a PR to get this fixed if it is agreeable.

            Assignee:
            tyler@10gen.com Tyler Brock
            Reporter:
            itay Itay Neeman
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: