如何使用python解析json元素?

时间:2016-01-13 03:59:22

标签: python json parsing xbmc kodi

我使用opener.open方法获取了json数据。现在我想参考它的元素。我尝试了以下代码,但我收到错误!此外,我想获得link =的值仅为link2。任何人都可以帮我解决这个错误并获得令牌的价值吗?提前谢谢。

代码:

   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"
    }

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分:1)

您可以尝试使用其他方法,

  import urllib2

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