Hp740319
Hp740319

Reputation: 747

loop in json after using JSON.Parser

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

Upvotes: 0

Views: 119

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599748

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)

Upvotes: 1

Related Questions