1

I'm using pymongo to fetch the data from the MongoDB database, then convert the cursor to JSON and get particular data.

The JSON data format, detailed_data:

[{'Column 0': 13.57557,
  'Column 1': 12.656892,
  'Column 2': -1.424328,
  'Column 3': -2.302774,
  'Column 4': 404.9216},
 {'Column 0': 13.844373,
  'Column 1': 12.61062,
  'Column 2': -1.435429,
  'Column 3': -1.964423,
  'Column 4': 404.97818},
 {'Column 0': 13.996934,
  'Column 1': 12.669785,
  'Column 2': -1.384147,
  'Column 3': -1.830788,
  'Column 4': 405.187378},
 {'Column 0': 14.060876,
  'Column 1': 12.755087,
  'Column 2': -1.378407,
  'Column 3': -2.02023,
  'Column 4': 404.892548},
 {'Column 0': 14.095317,
  'Column 1': 12.877163,
  'Column 2': -1.363435,
  'Column 3': -2.072163,
  'Column 4': 404.698822}]

The JSON data format; result

[{'_id': ObjectId('606702b2b1e51ef27782dcf5'),
  'FileName': 'ex.csv',
  'BriefInfo': '',
  'Size': '193.9KB',
  'UserName': '12795757',
  'data': [{'Column 0': 13.57557,
    'Column 1': 12.656892,
    'Column 2': -1.424328,
    'Column 3': -2.302774,
    'Column 4': 404.9216},
   {'Column 0': 13.844373,
    'Column 1': 12.61062,
    'Column 2': -1.435429,
    'Column 3': -1.964423,
    'Column 4': 404.97818},
   {'Column 0': 13.996934,
    'Column 1': 12.669785,
    'Column 2': -1.384147,
    'Column 3': -1.830788,
    'Column 4': 405.187378},
   {'Column 0': 14.060876,
    'Column 1': 12.755087,
    'Column 2': -1.378407,
    'Column 3': -2.02023,
    'Column 4': 404.892548},
   {'Column 0': 14.095317,
    'Column 1': 12.877163,
    'Column 2': -1.363435,
    'Column 3': -2.072163,
    'Column 4': 404.698822}]

Here is the code: I'm trying to put detailed_data and result into a python list and then convert it to JSON again. But I get an error:

Object of type ObjectId is not JSON serializable

Why did this error happen?

import json
import pymongo
from bson.json_util import dumps
from bson.json_util import loads
import random
import pandas as pd
import numpy as np
import csv
client = pymongo.MongoClient('username:password')
db = client.datasets


result = db.files.find({"FileName":"ex.csv","UserName":"12795757"})

result = loads(dumps(result))
detailed_data = result[0]["data"]
json.dumps([detailed_data, result])
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jay Park
  • 308
  • 1
  • 6
  • 14
  • Does this answer your question? [TypeError: ObjectId('') is not JSON serializable](https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable) – wuerfelfreak Apr 11 '21 at 09:37

1 Answers1

1

You should use json.encode(result, cls=JSONEncoder) since, mongodb result contains other meta data along with the result. i.e. it looks like JSON but it's not JSON.

Chirag Jain
  • 201
  • 3
  • 8