2016-01-13 104 views
1

我用opener.open方法得到了json數據。現在我想參考它的elmentS。我嘗試了下面的代碼,但我得到錯誤!此外,我想僅爲鏈接2獲取token =的值。任何人都可以幫助我解決這個錯誤並獲得令牌的價值嗎?提前致謝。如何使用python解析json元素?

代碼:

resp2 = opener.open('http://somewebsite.com/test/id',post_data) 
     print resp2.read() 
     Response = resp2.read(); 
     j_obj = json.load(Response) 
     print j_obj['link2'] 

錯誤:

ERROR: EXCEPTION Thrown (PythonToCppException) : 
-->Python callback/script returned the following error<-- 
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS! 
Error Type: <type 'exceptions.AttributeError'> 
Error Contents: 'str' object has no attribute 'read' 
j_obj = json.load(Response) 
line 286, in load 
return loads(fp.read(), 
AttributeError: 'str' object has no attribute 'read' 
-->End of Python script error report<-- 

JSON數據:

{ 
     "id": 1, 
     "name": "Test World", 
     "link1": "rtmp:\/\/me.someWebsite.com:1234\/static\/testWorld1?token=123456789abcdefghijklmnopqr&e=987654321&u=99999", 
     "link2": "http:\/\/me.someWebsite.com:1234\/testWorld1\/index.m3u8?token=123456789abcdefghijklmnopqr&e=987654321&u=99999&channel=testWorld1", 
     "image": "http:\/\/me.someWebsite.com\/img\/1\/2\/3\/4\/56.png", 
     "net": "rtmp:\/\/me.someWebSite.com:1234\/static", 
     "url": "testWorld1?token=123456789abcdefghijklmnopqr&e=987654321&u=99999", 
     "favorite": false, 
     "date": "2014-05-1" 
    } 
+1

'json.load()'是文件類型的對象,'json.loads()'是用於字符串。 – AChampion

回答

2

執行以下操作 - 注意resp2已經是一個string

resp2 = opener.open('http://somewebsite.com/test/id',post_data) 
print resp2 # You can verify you are receiving JSON data here. 
j_obj = json.loads(resp2) 
print j_obj['link2'] 
+0

感謝您的回覆。我現在嘗試它現在我得到這個錯誤:錯誤類型:錯誤內容:沒有JSON對象可以被解碼Traceback(最近呼叫最後): – user1788736

+0

打印您收到的字符串。發佈它包含的內容。 –

+0

非常感謝我刪除了Response = resp2.read();並使用resp2現在我得到了link2的值。我怎麼能得到該鏈接2上的標記的值?(標記= 123456789abcdefghijklmnopqr) – user1788736

1

你可以嘗試使用不同的方法,

import urllib2 

    post_data = ... 
    fp = urllib2.urlopen('http://somewebsite.com/test/id', post_data) 
    resp = fp.read() 
    print(resp)