pythonjsondjangodjango-rest-frameworkjsondecoder

raise JSONDecodeError("Expecting value", s, err.value) from None Python


I sometimes have this problem. But it's always resolved. This time impossible to find a solution. There are many post for the same subject but no resolution in my case. I am trying to get data from my api. It sometimes works(with data without none value) and with the data containing None value, it doesn't work. I think the problem is about the none values. I have this error

Exception Type: JSONDecodeError
Exception Value:    
Expecting value: line 1 column 75 (char 74)

Any help is appreciated.

@api_view(['GET'])
def edges_of_a_network(request, pk):
    try:
        roadnetwork = RoadNetwork.objects.get(pk=pk)
    except RoadNetwork.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    else:
        edges = Edge.objects.filter(network=roadnetwork)
        edges = str(list(edges.values("edge_id", "name",
            "length", "speed", "lanes"))).replace("'",'"')
        edges = json.loads(edges)
        edges = json.dumps(edges, indent=2)

    if request.method == 'GET':
        return HttpResponse(edges, content_type="application/json")

screenshot enter image description here


Solution

  • I finally find the solution to my problem. I add this line edges = edges.replace('None', "null"). I replace None values by null values

    @api_view(['GET'])
    def edges_of_a_network(request, pk):
        try:
            roadnetwork = RoadNetwork.objects.get(pk=pk)
        except RoadNetwork.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    
        else:
            edges = Edge.objects.filter(network=roadnetwork)
            edges = str(list(edges.values("edge_id", "name",
                "length", "speed", "lanes"))).replace("'",'"')
            edges = edges.replace('None', "null")
            edges = json.loads(edges)
            edges = json.dumps(edges, indent=2)
    
        if request.method == 'GET':
            return HttpResponse(edges, content_type="application/json")