Search code examples
pythonjsonparsingxbmckodi

How to parse json elements using python?


I got json data using opener.open method. Now I want to reference its elmentS. I tried the following code but i get error! Furthermore , I want to get the value of token= only for the link2 . Could any one help me fix this error and get value of token ? Thanks in advance.

code:

   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:

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 data :

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

Solution

  • Do the following - note that resp2 is already a 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']