2017-02-26 9 views
1

私は、次のjsonResponseオブジェクトで返されたデータにアクセスしたい:DjangoのユニットテストでJsonResponseでキーと値のペアにアクセス

{"results": [[1, "Probability and Stochastic Processes", 9781118324561, "Roy D. Yates", "2014-01-01", "Wiley"], [2, "Interaction Design", 9781119020752, "Rogers Price", "2015-01-01", "John Wiley & Sons"], [3, "Microeconomics", 9780077501808, "Colander", "2013-01-01", "McGraw Hill"], [4, "jfalksdjf", 123123, "test", "1990-01-01", "Penguin"]]} 

私はしかし、トラブルに実行していると私は

多くのことを試してみました
def test_noIDGiven(self): 
    response = self.client.get(reverse('allTextbooks')) #returns the json array above 
    #check that there are three textbooks in the response 
    #print(response.content['results'][0][0]) - this didnt work 
    self.assertEquals(response.content[0][0], 1) #basically want to access the id of the first object and make sure it is 1 

このオブジェクトのキー値のペアにアクセスする最善の方法がどのように優れているかについてのヘルプ。おかげで事前に

詳細情報: - i 'はallTextbooks' API呼び出しが戻るこの逆とき:

results = list(Textbook.objects.values_list()) 
return JsonResponse({'results': results}) 

答えて

1

今、

for k,v in response_dict: 
    for i in v: 
     id_list.append(i[0]) 

id_listはすべてのIDのあなたのリストです。

+1

.textはレスポンスの属性ではなく、response.contentを試してみると「JSONオブジェクトはstrでなければならない」というエラーが発生する – user4151797

1

をあなたは[0] [0] [ '結果']応答してみてくださいましたか?

そして、あなたが応じて各項目に簡単にアクセスしたい場合、あなたはこれを試すことができます:私は

import json 
response_dict = json.loads(response.text) 
id_list = [] 

、あなたが最初の辞書にあなたの応答を変換しようとしなければならないと思います

for item in response['results']: 
    print item[0] 
+0

はい私は応答['results'] [0] [0]を実行しました、そして、 'results'でキーエラーを受けました – user4151797

+0

あなたは "response = self.client.get(reverse 'allTextbooks')))?そのエラーが発生した場合はjsonではありません –

0

あなたはUTF-8(または何でも)として、その後、辞書にJSONとしてそれを解析することをデコードする必要がありますので、応答内容がそうのように、単にバイトであることをおっしゃるとおり

response = self.client.get(reverse('allTextbooks')) 
self.assertEqual(response.status_code, 200) 
self.assertEqual(response['Content-Type'], 'application/json') 
j = json.loads(response.content.decode('utf-8')) 
self.assertEqual(j['results'][0][0], 1) 

私は、応答が成功し、JSONとしてフラグが立てられていることを検証するためにいくつかのアサーションを追加しましたが、それらはオプションです。

関連する問題