Python:当我尝试将JSON文件插入Mongodb时,如果json文件无效,则抛出error.how来捕获错误

时间:2018-05-23 10:17:36

标签: python mongodb pymongo

您好我正在尝试将json文件插入mongoDb.I已编写代码并且对我来说工作正常。



import sys, json, pymongo,glob
from pymongo import MongoClient
from bson import json_util
from multiprocessing.sharedctypes import template
from json.decoder import JSONDecodeError
from itertools import count


connection = MongoClient('localhost',27017)
db = connection.Mysample
mycollection = db.Mynewsample
folder = 'C:/ESRILKA/Cloud Team/Tmobile/JSON To CSV  Files/JSON files/*.json'
jsonFiles = glob.glob(folder)
for file in jsonFiles:
    with open(file) as template:
                      
                try:                
                    template_dct=json.load(template)
                    result = db.Mynewsample.insert_one(template_dct)                    
                    print('Inserted post id %s ' % result.inserted_id)
                    
                except (ValueError, KeyError, TypeError) as e:
                        print("Invalid json at")
                        pass
            
                 




但是现在我想在插入之前验证json文件。如果json无效,它应该显示一条消息说"解析失败等等。"

1 个答案:

答案 0 :(得分:0)

使用try,除外。一个例子:

import json


def is_valid_json(json_string):
    try:
        json.loads(json_string)
    except:
        return False
    return True


# Return True
print(is_valid_json('{"name": "Jhon"}'))

# Return False
print(is_valid_json("{'name': 'Jhon'}"))

Demo