Search code examples
pythonjsonpymongo

(pymongo) passing Json as return function input


I just know we cannot directly pass json to function
that I learn from sending json object to function python

so that I used json.dumps() transform into str when input in function, and return back to json format by json.loads()

but there still cannot run properly, what is the reason, and is there any simple way?

python code (pymongo):

import pymongo
import datetime
import json

myclient = pymongo.MongoClient("mongodb://localhost:27017/users")

def Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json_inStr_list):
    
    mydb_Name= input_new_DB_name

    mydb = myclient[mydb_Name]

    existing_DB = myclient.list_database_names()

    dblist = myclient.list_database_names()
    if mydb_Name in dblist:
      boolean_db_exist = True

    mycol = mydb["input_new_collection_name"]

    existing_collection = mydb.list_collection_names()

    collist = mydb.list_collection_names()
    if "input_new_collection_name" in collist:
      boolean_collection_exist = True

    json_input_end = json.loads(input_json_inStr_list)
    x = mycol.insert_many(json_input_end)

    Inserted_data = x.inserted_ids

    return existing_DB, existing_collection, Inserted_data


input_new_DB_name = input("Enter ur new DB name: ")
input_new_collection_name = input("Enter ur new collection name: ")
input_json = input("Enter the json input: ")
input_json_inStr_list = json.dumps(input_json)


list_of_DB ,list_of_collection, new_insert_data = Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json)

print(list_of_DB)
print(list_of_collection)
print(new_insert_data)

my input:

Enter ur new DB name: 111112333
Enter ur new collection name: wwfsvdf
Enter the json input: [{"name": "Joy", "ID": "000111", "Age": 23 , "time" : json_datetime},{ "name": "Tom", "ID": "000222", "Age": 88, "time" : json_datetime} ]

Enter ur new DB name: 111112333
Enter ur new collection name: wwfsvdf
Enter the json input: [{"name": "Joy", "ID": "000111", "Age": 23 , "time" : json_datetime},{ "name": "Tom", "ID": "000222", "Age": 88, "time" : json_datetime} ]
Traceback (most recent call last):
  File "C:\Users\chuan\OneDrive\Desktop\10.13_connect_mongoDB\insert_collection.py", line 51, in <module>
    list_of_DB ,list_of_collection, new_insert_data = Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json)
  File "C:\Users\chuan\OneDrive\Desktop\10.13_connect_mongoDB\insert_collection.py", line 36, in Create_DB_save_data
    json_input_end = json.loads(input_json_inStr_list)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 55 (char 54)

I just tried again with input Json format list

import pymongo
import datetime
import json

myclient = pymongo.MongoClient("mongodb://localhost:27017/users")

def Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json):
    
    mydb_Name= input_new_DB_name

    mydb = myclient[mydb_Name]

    existing_DB = myclient.list_database_names()

    dblist = myclient.list_database_names()
    if mydb_Name in dblist:
      boolean_db_exist = True

    mycol = mydb["input_new_collection_name"]

    existing_collection = mydb.list_collection_names()

    collist = mydb.list_collection_names()
    if "input_new_collection_name" in collist:
      boolean_collection_exist = True

    My_list = []
    My_list.append(input_json) 
    x = mycol.insert_many(My_list)

    Inserted_data = x.inserted_ids

    return existing_DB, existing_collection, Inserted_data


input_new_DB_name = input("Enter ur new DB name: ")
input_new_collection_name = input("Enter ur new collection name: ")
input_json = input("Enter the json input: ")


list_of_DB ,list_of_collection, new_insert_data = Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json)

print(list_of_DB)
print(list_of_collection)
print(new_insert_data)

output still getting error though(I know it should work, so maybe somewhere is wrong):

Enter ur new DB name: (practice_10_14)-0002
Enter ur new collection name: (practice_10_14)_customer_data
Enter the json input: [{"name": "Joy", "ID": "000111", "Age": 23 , "time" : json_datetime},{ "name": "Tom", "ID": "000222", "Age": 88, "time" : json_datetime} ]
Traceback (most recent call last):
  File "C:\Users\chuan\OneDrive\Desktop\10.13_connect_mongoDB\insert_collection.py", line 42, in <module>
    list_of_DB ,list_of_collection, new_insert_data = Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json)
  File "C:\Users\chuan\OneDrive\Desktop\10.13_connect_mongoDB\insert_collection.py", line 30, in Create_DB_save_data
    x = mycol.insert_many(My_list)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\pymongo\_csot.py", line 105, in csot_wrapper
    return func(self, *args, **kwargs)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\pymongo\collection.py", line 706, in insert_many
    blk.ops = [doc for doc in gen()]
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\pymongo\collection.py", line 706, in <listcomp>
    blk.ops = [doc for doc in gen()]
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\pymongo\collection.py", line 697, in gen
    common.validate_is_document_type("document", document)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\pymongo\common.py", line 521, in validate_is_document_type
    raise TypeError(
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

The TypeError: document must be an instance of dict ... made me thought I need transfer to string(but no need)


Solution

  • the return function can pass Jason as input, this is correct I was stock on line42 that input_json_str = input("Enter the json input: ") the input(" ") will defult take what ever data as string

    and I transfer by json.loads() as Json data input intp function

    
    import pymongo
    import datetime
    import json
    
    myclient = pymongo.MongoClient("mongodb://localhost:27017/users")
    
    def Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json):
        
        mydb_Name= input_new_DB_name
    
        mydb = myclient[mydb_Name]
    
        existing_DB = myclient.list_database_names()
    
        dblist = myclient.list_database_names()
        if mydb_Name in dblist:
          boolean_db_exist = True
    
        mycol = mydb["input_new_collection_name"]
    
        existing_collection = mydb.list_collection_names()
    
        collist = mydb.list_collection_names()
        if "input_new_collection_name" in collist:
          boolean_collection_exist = True
    
        My_list = []
        My_list.append(input_json) 
        x = mycol.insert_many(My_list)
    
        Inserted_data = x.inserted_ids
    
        return existing_DB, existing_collection, Inserted_data
    
    
    input_new_DB_name = input("Enter ur new DB name: ")
    input_new_collection_name = input("Enter ur new collection name: ")
    input_json_str = input("Enter the json input: ")
    input_json =json.loads(input_json_str)
    
    list_of_DB ,list_of_collection, new_insert_data = Create_DB_save_data(input_new_DB_name, input_new_collection_name, input_json)
    
    print(list_of_DB)
    print(list_of_collection)
    print(new_insert_data)
    

    output:

    C:\Users\chuan\OneDrive\Desktop\10.13_connect_mongoDB>python insert_collection.py
    Enter ur new DB name: (practice_10_14)-0004444
    Enter ur new collection name: (practice_10_14)_customer_dataffffff
    Enter the json input: {"name222222":"joy22222","age":22}
    ['(practice_10_14)', '(practice_10_14)-0001', '(practice_10_14)-0002', 'admin', 'cloud_db', 'cloud_db_back', 'config', 'gz_test', 'local']
    []
    [ObjectId('634921b57c8cbbe1dd2d1e97')]