Search code examples
pythonpandasmongodbdataframepymongo

Python Pandas: Dataframe to_json not index oriented


The default Dataframe.to_json() exports like this:

{
    "date": {
        "0": Example_date1,
        "1": Example_date2
    }
    "name": {
        "0": Example_name1,
        "1": Example_name2,
    }
}

I want the json to be document oriented for MongoDB, like this:

{
    {
        "date": Example_date1,
        "name": Example_name1
    }
    {
        "date": Example_date2,
        "name": Example_name2,
    }
}

I got this problem, because I want to read data from MongoDB database and when I load into a Dataframe, it gets only one line. I think it's better to send a json document oriented. I am new to working with MongoDB and NoSQL structures, so if you have a suggestion I'd be happy to read it.


Solution

  • If you use .to_dict(orient="records") you get this output:

    [
        {'date': 'Example_date1', 'name': 'Example_name1'}, 
        {'date': 'Example_date2', 'name': 'Example_name2'}
    ]
    

    If you really needed the mentioned format then I suggest this:

    dict_df = df.to_dict(orient="records")
    formatted_dict = str(dict_df).replace("[", "{").replace("]", "}")