2016-12-05 60 views
-1

尊重, 我trig是使用與base64編碼的json文件的內容。 我想解碼json文件的編碼部分。以下是我的代碼。提取JSON文件在base64解碼

response={"response": [{"objcontent": [{"rowkeys":["time","lat","lon","tos"],"rowvalues": [["AAAAAAAALkA=","AAAAAADgU8A=","AAAAAAAA8D8=","7HitYA"],["AAAAAAAALkA=","AAAAAADgU8A=","AAAAAAAACEA=","7HitYA"],["AAAAAAAALkA=","AAAAAADgU8A=","AAAAAAAAFEA=","7HitYA"]]}]}]} 

import base64 
import struct 
for response_i in response['response']: 
    a=base64.b64decode(response_i['objcontent'][0]['rowvalues']) 
    struct.unpack('12d',a) 

以下是我得到的錯誤。

TypeError: argument should be a bytes-like object or ASCII string, not 'list' 

可能有人提供一些技巧來解決這個問題。 謝謝。

+1

重新讀取錯誤信息。 –

+0

你有**列表**的字符串,而不是一個字符串。 –

回答

1

你傳遞你的整個列表,它本身包含多個列表:

>>> response_i['objcontent'][0]['rowvalues'] 
[['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAA8D8=', '7HitYA'], ['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAACEA=', '7HitYA'], ['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAAFEA=', '7HitYA']] 

你需要解碼每個單獨的條目,而不是整個列表:

for response_i in response['response']: 
    for row in response_i['objcontent'][0]['rowvalues']: 
     for encoded_obj in row[:-1]: 
      decoded = base64.b64decode(encoded_obj) 

注意,我忽略的該行中的最後一個值,這不是Base64值。

你的未來問題是你的Base64數據沒有足夠的字節來保存12個浮點值(每個8字節,所以你需要96字節)。由於它們分別是8字節,所以每個字符串中可能只有一個一個浮點值。

所以,你會想只是一個浮動解碼:

floating_point_value = struct.unpack('d', decoded)[0] 

演示:

>>> for response_i in response['response']: 
...  for row in response_i['objcontent'][0]['rowvalues']: 
...   for encoded_obj in row[:-1]: 
...    decoded = base64.b64decode(encoded_obj) 
...    print(struct.unpack('d', decoded)[0]) 
... 
15.0 
-79.5 
1.0 
15.0 
-79.5 
3.0 
15.0 
-79.5 
5.0 
0

你的json似乎是畸形的,還有更多的開放[比關閉]。所以我不能給你一個確切的分解。

無論如何,與鍵'rowvalues'匹配的值是列表[[],[],[]]的列表。所以,你需要相應地打破它以正確的價值觀傳遞給解碼器

for value_list in response_i['objcontent'][0]['rowvalues']: 
    for value in value_list: 
     # enter your decode code here 
0

這確實以base64解碼,將struct.unpack我失敗。

import base64 
import struct 

response = { 
    "response": [{ 
     "objcontent": [{ 
      "rowkeys": ["time", "lat", "lon", "tos"], 
      "rowvalues": [ 
       ["AAAAAAAALkA=", "AAAAAADgU8A=", "AAAAAAAA8D8=", "7HitYA"], 
       ["AAAAAAAALkA=", "AAAAAADgU8A=", "AAAAAAAACEA=", "7HitYA"], 
       ["AAAAAAAALkA=", "AAAAAADgU8A=", "AAAAAAAAFEA=", "7HitYA"] 
      ] 
     }] 
    }] 
} 


for response_i in response['response']: 
    for r in response_i['objcontent'][0]['rowvalues']: 
     for item in r[:-1]: # last item doesnt seem to be be base64 encoded ! 
      a = base64.b64decode(item) 
      print a 
      # .... whatever ... struct.unpack('12d',a)