2009-12-11 18 views
2

具体来说,我得到了一个调用Django的服务形式(使用活塞写的,但我不认为这是相关的),通过POST像这样发送:Django,Python:有没有简单的方法将PHP式的括号内POST键转换为多维字典?

edu_type[3][name] => a 
edu_type[3][spec] => b 
edu_type[3][start_year] => c 
edu_type[3][end_year] => d 
edu_type[4][0][name] => Cisco 
edu_type[4][0][spec] => CCNA 
edu_type[4][0][start_year] => 2002 
edu_type[4][0][end_year] => 2003 
edu_type[4][1][name] => fiju 
edu_type[4][1][spec] => briju 
edu_type[4][1][start_year] => 1234 
edu_type[4][1][end_year] => 5678 

我想处理此上Python结束得到这样的事情:

edu_type = { 
    '3' : { 'name' : 'a', 'spec' : 'b', 'start_year' : 'c', end_year : 'd' }, 
    '4' : { 
     '0' : { 'name' : 'Cisco', 'spec' : 'CCNA', 'start_year' : '2002', 'end_year' : '2003' }, 
     '1' : { 'name' : 'fiju', 'spec' : 'briju', 'start_year' : '1234', 'end_year' : '5678' }, 
    }, 
} 

任何想法?谢谢!

+0

觉得我不是你想要做什么明确的。你想在下面的字典就像你上面的那个。原始数据是什么? PHP风格的括号内容是什么意思? – McPherrinM 2009-12-11 21:01:07

+0

HTTP POST(一个PUT,但在这里不相关)允许发送名称/值对作为字符串。上面的代码表示一个这样的POST,左侧的名称字符串和右侧的值。 PHP采用了一种技巧,使得通过POST请求传递多维数组变得简单:当上面的语法被发布到PHP脚本时,它可以作为本地数组立即在$ _POST superglobal中使用。由于这个技巧,PHP程序员在发送数据时往往不会考虑两次,这是我得到的问题 - 我没有访问调用代码的权限。 – 2009-12-11 21:32:37

+0

那么你是否会收到一个字符串,看起来像你的第一个代码块中的代码?或者你得到一个Python对象? – andylei 2009-12-12 00:13:05

回答

0

我骑过上一个响应由阿特利关于使用PHP的json_encode ...

Python字典在其最基本的形式是语法上等同于JSON。你可以很容易地进行对JSON结构的eval()创建一个Python字典:

>>> blob = """{ 
...  '3' : { 'name' : 'a', 'spec' : 'b', 'start_year' : 'c', 'end_year' : 'd' }, 
...  '4' : { 
...   '0' : { 'name' : 'Cisco', 'spec' : 'CCNA', 'start_year' : '2002', 'end_year' : '2003' }, 
...   '1' : { 'name' : 'fiju', 'spec' : 'briju', 'start_year' : '1234', 'end_year' : '5678' }, 
...  }, 
... }""" 
>>> edu_type = eval(blob) 
>>> edu_type 
{'3': {'end_year': 'd', 'start_year': 'c', 'name': 'a', 'spec': 'b'}, '4': {'1': {'end_year': '5678', 'start_year': '1234', 'name': 'fiju', 'spec': 'briju'}, '0': {'end_year': '2003', 'start_year': '2002', 'name': 'Cisco', 'spec': 'CCNA'}}} 

现在,这是最好的办法吗?可能不会。但它的工作原理并不诉诸正则表达式,这在技术上可能会更好,但考虑到调试和排除模式匹配故障所花费的时间,绝对不是一个更快的选项。

JSON是用于插页式数据传输的良好格式。

Python也有一个json模块作为标准库的一部分。虽然这对你正在解析的输出更挑剔,但它肯定是更好的方式去做(尽管涉及更多的工作)。

0

好,所以这是贫民窟的地狱,但这里有云:

让我们说你的投入是一个元组列表。说:输入= [( 'edu_type [3] [END_YEAR]', 'd'),...]

from collections import defaultdict 
from re import compile 

def defdict(): 
    return defaultdict(defdict) 
edu_type = defdict() 

inputs = [(x.replace('[', '["').replace(']', '"]'), y) for x, y in input] 
for input in inputs: 
    exec = '%s = "%s"' % input 

请注意,如果你信任你的输入源,你应该只使用它,因为它远不是安全的。

1

Dottedish做你想要的东西。 http://pypi.python.org/pypi/dottedish。它没有一个真正的主页,但你可以从pypi安装它,或者从github下载源代码。

>>> import dottedish 
>>> dottedish.unflatten([('3.name', 'a'), ('3.spec', 'b')]) 
{'3': {'name': 'a', 'spec': 'b'}} 
相关问题