如何使用 python 解析 json 元素?

How to parse json elements using python?

我使用 opener.open 方法获得了 json 数据。现在我想引用它的 elmentS。我尝试了以下代码,但出现错误!此外,我只想为 link2 获取 token= 的值。谁能帮我解决这个错误并获得令牌的价值?提前致谢。

代码:

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

执行以下操作 - 请注意 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']

您可以尝试使用不同的方法,

  import urllib2

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