which is the best way to get the value of 'session_key','uid','expires'
i have a string
''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164 23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679开发者_StackOverflow中文版bbeed4282154b35"} '''
how to get the value .
thanks
>>> 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'
>>>
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']
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.
精彩评论