I have some information stored in JSON format and I am looking to transform it into a CSV file

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;
int main()
{
    ofstream myfile;
    myfile.open("newtest.csv");
    mongocxx::instance instance{};
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client client(uri);
    mongocxx::database db = client["work"];
    mongocxx::collection coll = db["User"];
    bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result = coll.find_one({});
}

JSON in maybe_result:

{
    "_id": {
        "$oid": "5f2a435186ff70fb16f873ec"
    },
    "first_name": "Gutta",
    "last_name": "sumanth",
    "age": 25.0,
    "employee_status": "active",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2f29313d3228341c3b313d3530723f3331">[email protected]</a>"
}

I intend to convert the output to CSV format.

Answer №1

My approach to achieve this task involves decoding a selection of bsoncxx::types, leaving the rest unexplored for simplicity's sake. For additional types required, their inclusion is necessary. However, the provided solution should suffice to convert your data into a format.

The utility functions have been encapsulated within a class to enable streaming to any std::ostream.

bson_csv_adapter.hpp

#ifndef BSON_CSV_ADAPTER_HPP_IUPAHOIUHASDUIKHLKHAD
#define BSON_CSV_ADAPTER_HPP_IUPAHOIUHASDU...
#include <ostream>

class BsonCSVadapter {
public:
    // Implementation using bsoncxx::document::view
    explicit ...
        return os << '\n';
    }

private:
    void ...

    template<typename It>
        }
    }

    template<typename ElType>
        switch(e.type()) { // bsoncxx::type
            case bsoncxx::type::k_double:
                os << e.get_double();
                break;
                
            case bsoncxx::type::k_int32:
                os << e.get_int32();
                break;

            case bsoncxx::type::k_utf8: {
                bsoncxx::stdx::string_view sv = e.get_utf8();
                os << ...
                break;
            }
            case bsoncxx::type::k_array: ...
            case bsoncxx::type::k_document: ...
        }
    }

    bsoncxx::document::view m_bdv;
};

// Overloaded operator for streaming
std::ostream& operator<<(std::ostream& os, const BsonCSVadapter& a) {
    return a.print(os);
}

#endif

In your .cpp file:

#include "bson_csv_adapter.hpp"

        // ...
           if(maybe_result) {
               std::cout << BsonCSVadapter(*maybe_result);

            std::ofstream myfile("newtest.csv");
            myfile << BsonCSVadapter(*maybe_result);
        }

Output:

5f2a435186ff70fb16f873ec,Gutta,sumanth,25,active,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d6d0c8c4cbd1cde5c2c8c4cc...       
          
If you choose to uncomment the line <code>os << e.key().to_string() << ':';, the output will be as follows:

_id:$oid:5f2a435186ff70fb16f873ec,first_name:Gutta,last_name:sumanth,age:25,employee_status:active,email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acdfd9c1cdc2d8c4e...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to add an object to an array in a collection, there was an issue with

In my application, I am accessing a collection in Mongodb using ReactJS and mongoose. One of the properties in this collection is set to an Array type. When I add elements to this Array, they are successfully added but for some reason, the _id field that ...

What do I need to add to my code in order to receive a JSON response from the URL I am

I developed a custom Python client REST API wrap for an authenticated Okta pricing API. Although my code is functional, I am not receiving any response. My goal is to retrieve a JSON response, and I have considered using a print statement, but I am unsur ...

Python's nested if conditions allow for more complex conditions to be

In a specific scenario, I am required to validate certain conditions within the provided JSON data and then take action accordingly. You can view the json data here. The condition that needs to be checked is as follows: Iterate through the JSON and ident ...

Transforming JSON data into a dynamic Tableview

I've been experimenting with this issue for quite some time now, but I can't seem to find a solution. My API returns tasks in JSON format. When I print the data using Ti.API.info(this.responseText), it looks like this: [INFO] [{"created_at":"20 ...

Can you explain how the tagging feature works in the comment section of platforms like Facebook or Azure, where users can mention others by using the '@' symbol?

I am currently working on creating a comment box application similar to Facebook using the MERN stack. While adding simple comments is not difficult, I am curious about how the tagging mechanism works when mentioning a user with an '@' symbol. Sh ...

Ways to retrieve the name of a JValue object

I have been working with Newtonsoft.Json to parse Json text, and I am trying to find a way to retrieve the name of a JToken or JValue object. For example, if "ChoiceId":865 is the value, I need to extract "ChoiceId". Despite spending hours on it, I haven&a ...

What is the solution for resolving the Angular error 'Cannot read property "_co.x" of undefined'?

Currently, I am facing an issue with nested JSON objects on a form that sends data to a database. Despite trying the *ngIf statement as recommended in Angular 5 - Stop errors from undefined object before loading data, the view does not update even after th ...

Using Dropwizard and Jersey for authenticating users and passing JSON parameters

Is there a way to create a REST interface method for a resource like the following example? @POST @Consumes(MediaType.APPLICATION_JSON) public void add(@Auth User user, @Valid Food food) { //consume } Unfortunately, attempting to implement this me ...

Traversing an array of objects with Node.js and MongoDB

I am currently learning how to use MongoDB and Node.js. I am facing an issue where I want to loop through an array of objects from my database and display all the objects using res.json. While in my console.log it shows all the objects, when I use res.json ...

Explore the information stored in two different arrays

Currently, I'm trying to access and load data from 2 arrays. I've managed to successfully load the items array within the first array. However, when attempting to access the data inside the second array, it fails to load. The JSON response conta ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

Is there a way to ensure that all asynchronous functions have finished executing before assigning them to module.exports?

Currently, I am working on developing an app that generates routes based on data retrieved from a MongoDB database using Mongoose. Here is the current setup: var app = express(); var articleRoute = require('./article.js'); var Articles = requi ...

How can I effectively communicate and share dependencies in a shared class?

After extending an abstract class and implementing a method specifically for use with Mule, I realized the need to add this functionality to a library that will be hosted on Maven Central. The catch is that this library relies on a JAR provided in the Mule ...

Tips for modifying the JSON array output into an object using PHP

I am encountering an issue with the API JSON output. I am experiencing some difficulties with the JSON output when it comes to looping through, as it seems to create its own indexes despite my attempts to force the array format into an indexed array. Here ...

What is the process for transferring a document from one database to another in couchDB?

Is it necessary to load a couchDB JSON document to the client first and then post it to another couchdb database in order to copy it from one db to another? Or is there a server-side method that can achieve this? Reference The copy command is non-standar ...

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

How can I retrieve the initial IP address from the 'X-Forwarded-For' using a Log Insight Query?

Can someone help me with extracting the initial IP address from the given data: X-Forwarded-For":"1.1.1.1, 2.2.2.2? This is the query I am currently using: fields @timestamp, @message | filter @message like /Endpoint request body after transform ...

Ways to eliminate the absence of the 'Access-Control-Allow-Origin' header in an error message when using a Java-based web-service server

I'm currently working on developing a webservice using Java as the server and Javascript as the client. My goal is to send a Post request with JSON data and receive a Post response with JSON data from the server. However, since the client and server h ...

Guide on how to add an array of objects in Mongoose using ExpressJS

I am looking to add a product with various sizes and prices but I'm experiencing an issue with storing this array of objects in MongoDB. Below is my Product Schema: const productSchema = new mongoose.Schema({ product_name: {type:String, required: ...

I am encountering the org.json.JSONException error message stating that there is no value for a specific item in my JSON array

Despite having "feels_like" in my JSON array, the error log is indicating that it is not present. CODE: protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject jsonObject = new JSONObject(s); ...