Python:当我尝试将JSON文件插入Mongodb,如果JSON文件无效,则抛出错误。怎么做为了抓住它

2024-09-30 08:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试将json文件插入mongoDb。我已经编写了代码,对我来说工作正常。你知道吗

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无效,它将显示一条消息,说明“解析失败等…”


Tags: 文件fromimportjsondbtemplatefolderconnection
1条回答
网友
1楼 · 发布于 2024-09-30 08:17:24

使用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

相关问题 更多 >

    热门问题