0

I'm Using Rest framework to get JSON data and parse them. now I don't know how to access the second argument of json data, for parse the json I've seen this link.

code in views:

@api_view(['POST'])
@parser_classes((JSONParser,))
def product_list(request):
    """
    List all products which name of them is in the json data
    """

    if request.method == 'POST':
        print(request.data)
        MarketProduct=[]
        for item in request.data:
            print(item)
            try:
                product=Market.objects.get(name=item)
                MarketProduct.append(product)
            except Market.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = MarketSerializer(MarketProduct, many=True)
        return Response(serializer.data)

code in urls:

urlpatterns = [

    url(r'^listproducts/$', views.product_list),


]

here in this line: for item in request.data: the item only has the first argument of each json.

the json which I've sent is :

{'hello': '1', 'bye': '2'}

in printing items , only "hello" and "bye" prints.but i want to access "1" and "2" too.

It's important for me to use Django framework. and I can't get the appropriate way to use json.load(raw) in this situation

1 Answer 1

1

This doesn't have anything to do with parsing JSON. DRF has already parsed the JSON into a Python dict, and you'd get exactly the same result if you used json.loads.

When you iterate through a dict, you just get the keys. To get the values as well, you need to iterate through .items():

for item, value in request.data.items():
        print(item, value)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.