tags:

views:

50

answers:

3

i have a string

''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164 23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679bbeed4282154b35"} '''

how to get the value .

thanks

+3  A: 
>>> import json
>>> s=''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":16423386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679bbeed4282154b35"} '''
>>> d=json.loads(s)

>>> d['session_key']
u'3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986'
>>> d['uid']
16423386
>>> d['expires']
12673200
>>> d['secret']
u'sm7WM_rRtjzXeOT_jDoQ__'
>>> d['sig']
u'6a6aeb66 64a1679bbeed4282154b35'
>>> 
gnibbler
+2  A: 

The string appears to be JSON.

import json
obj= json.loads( aString )
obj['session_key']

Or it could be a Python dict. Try

obj= eval(myString)
obj['session_key']
S.Lott
`eval` is evil. Even if it *could* be a Python dict, you can't be sure that that string won't contain anything bad.
poke
@poke: Actually, you can be very sure the string doesn't contain anything bad. If you don't get strings from malicious sociopaths, you can be assured they are safe. If, however, you have malicious sociopaths on staff, you should not accept anything from them, including Python strings.
S.Lott
A: 

For a simple-to-code method, I suggest using ast.parse() or eval() to create a dictionary from your string, and then accessing the fields as usual. The difference between the two functions above is that ast.parse can only evaluate base types, and is therefore more secure if someone can give you a string that could contain "bad" code.

Lay