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

BSONArray jsonString() always prints as object

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major - P3
    • Resolution: Fixed
    • Affects Version/s: legacy-0.0-26compat-2.6.0, legacy-0.8.0
    • Fix Version/s: legacy-0.11.0
    • Component/s: BSON
    • Labels:

      Description

      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.

        Attachments

          Issue Links

            Activity

              People

              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: