![](/img/trans.png)
[英]How to fix this error json.decoder.JSONDecodeError: Python
[英](Django, Python) How do I fix json.decoder.JSONDecodeError?
我一直在尝试为三明治店制作订单/购物车应用程序。 在我进行测试时,我不断收到与解码前端工程师发送给我的 JSON 数据有关的错误。
下面是服务器收到的 POST 请求。
{
"default_ingredients": [
{
"id": 1,
"name": "이탈리안 화이트 (top)",
"image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_BreadItalian_customizer_large.png",
"price": "0.00",
"ingredient_category_id": 1
},
{
"id": 23,
"name": "토마토",
"image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/OptionsIds/10133_customizer_large.png",
"price": "0.00",
"ingredient_category_id": 3
},
],
"added_ingredients": [
{
"id": 18,
"name": "살라미",
"image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_TurkeyBasedHamSalamiBologna_customizer_large.png",
"price": "0.00",
"ingredient_category_id": 2
},
{
"id": 19,
"name": "페퍼로니",
"image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_Pepperoni_customizer_large.png",
"price": "1800.00",
"ingredient_category_id": 2
},
],
"product_name": "이탈리안 비엠티",
}
以下是订单应用程序的views.py
import json
import ast
import jwt
import bcrypt
from django.views import View
from django.http import JsonResponse
from .models import (
Order,
Cart,
CartIngredient,
DestinationLocation,
OrderStatus
)
from product.models import (
Product,
Category,
SubCategory,
Nutrition,
Ingredient,
ProductIngredient
)
from store.models import Store
from account.models import Customer
from codesandwich.settings import SECRET_KEY
def login_required(func):
def wrapper(self, request, *args, **kwargs):
header_token = request.META.get('HTTP_AUTHORIZATION')
decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email']
try:
if Customer.objects.filter(email=decoded_token).exists():
return func(self, request, *args, **kwargs)
else:
return JsonResponse({"message": "customer does not exist"})
except jwt.DecodeError:
return JsonResponse({"message": "WRONG_TOKEN!"}, status=403)
except KeyError:
return JsonResponse({"message": "Key Error"}, status=405)
except Customer.objects.filter(email=decoded_token).DoesNotExist:
return JsonResponse({"message": "User Not Found"}, status=406)
return wrapper
class CartView(View):
@login_required
def post(self, request):
#import pdb; pdb.set_trace()
######### PART THAT NEEDS TO BE FIXED ################################
body = json.loads(request.body).decode('utf-8') #
######################################################################
## must receive user info
## decoded_token -> email -> filter(email=email) -> retrieve id
header_token = request.META.get('HTTP_AUTHORIZATION', '')
decoded_token = jwt.decode(header_token,SECRET_KEY, algorithm='HS256')['email']
customer_id = Customer.objects.get(email=decoded_token).id
a = Customer.objects.get(id=customer_id)
## below is when the customer's order is still active
if Order.objects.filter(customer_id = customer_id).last().order_status.id == 2:
## update the order by just adding carts
order_id = Order.objects.filter(customer = a).last().id
order = Order.objects.get(id = order_id)
if body['product']:
product_id = body['product']['id']
product = Product.objects.get(id = product_id)
#this extracts the price
price = body['product']['default_price']
price = float(price)
## make a new cart for default_item
Cart.objects.create(order = order, price = price, amount = 1, product = product)
order.total_price += price
order.save()
有问题的部分就在“class CartView(View)”的正下方
这是错误消息:
> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(52)post()->None
-> body = json.loads(request.body).decode('utf-8')
(Pdb) next
json.decoder.JSONDecodeError: Expecting value: line 17 column 2 (char 636)
> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(36)wrapper()
-> return func(self, request, *args, **kwargs)
我应该怎么做才能避免这个错误? 我也尝试过 ast ,但它仍然对我不起作用。
我找到了答案。 答案是在使用 ast 评估之前使用“utf-8”解码。
body = ast.literal_eval(request.body.decode('utf-8'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.