我正在使用Python编写CRUD操作(特别是创建和读取)。我正在编写一个测试脚本来创建和读取字典,以便稍后在mongoDB shell中使用,并且遇到了一个JSONDecodeError
我是python和JSON新手,以前从未遇到过这个错误。如何修复此错误?还有,有什么方法可以改进我正在编写的代码吗
谢谢大家!
以下是我的测试脚本:
from pymongo import MongoClient
from bson.objectid import ObjectId
import CRUD
from CRUD import AnimalShelter
import random
import string
import json
shelter = AnimalShelter()
animal_id = 'A'.join(random.choices(string.ascii_uppercase + string.digits, k=6))
print('animal_id %s being created' % animal_id)
outcome = json.loads(
'{"": 78258, "age_upon_outcome": "1.6 years", "animal_id": "" + animal_id + "", "animal_type": "Dog", "breed": "Wolf Sheperd Mix", "color": "Grey", "date_of_birth": "2013-02-09", "datetime": "2014-04-11 13:26:00", "month_year": "2014-04-11T13:26:00", "name": "*JakeMo", "outcome_subtype": "Partner", "outcome_type": "Transfer", "sex_upon_outcome": "Intact Male", "Location_lat": "30.707721081886, "location:long": "-97.2735696278757", "age_upon_outcome_in_weeks": 110.0799603174603}')
#print(outcome)
if shelter.create(outcome):
print("animal added")
animal = shelter.read({"animal_id":animal_id})
print(animal)
问题在于这些线路:
您在这里所做的是创建一个字符串,然后使用
json.loads
将其解析为dict。当您可以直接创建dict时,这样做没有任何意义:理论上,您可以通过(a)更改
animal_id
周围的引号(注意下面和我的答案顶部代码段中突出显示animal_id
变量的差异)和(b)修复Location_lat
属性值后缺少的双引号,从而使JSON解析工作正常。但正如我已经解释的那样,这不是最好的做法相关问题 更多 >
编程相关推荐