您可以尝试使用向后兼容 Python 2.5 的pyparsing - 请参阅下面带注释的代码中的注释:
from pyparsing import Suppress, Forward, Word, nums, quotedString, removeQuotes, alphas, alphanums, Group, delimitedList
# define some punctuation expressions
LBRACE,RBRACE,COLON = map(Suppress,"{}:")
# forward declare dict_, because we will use it as part of defining
# dict_value, which we will then use to define dict_ (i.e., the grammar
# is recursive)
dict_ = Forward()
# what does a key value look like (guessing it is any word that
# starts with an alpha or '_', followed by zero or more alphas, nums, or '_'s)
dict_key = Word(alphas+'_',alphanums+'_')
# define possible values for dict entries (expand as needed)
# parse actions do data conversion during parsing, so that we get native Python types,
# not just strings for everything that we have to convert later
integer = Word(nums).setParseAction(lambda t:int(t[0]))
quotedString.setParseAction(removeQuotes)
dict_value = quotedString | integer | dict_
# a dict element is key : value
dict_element = Group(dict_key + COLON + dict_value)
# use a parse action to convert parsed data to dicts while parsing
make_dict = lambda t: dict(t.asList())
# finally, define dict_ using '<<' operator to "inject" the pattern into the previously
# defined Forward - delimitedList(expr) is a short-cut for expr + ZeroOrMore(',' + expr)
dict_ << (LBRACE + (delimitedList(dict_element).setParseAction(make_dict) + RBRACE))
# parse the input string - we get back a real dict, not just a hierarchical list of strings
data = "{first : {name : 'test', value : 100}, second : {name : 'test2', value : 50}}"
dd = dict_.parseString(data)[0]
print type(dd)
print dd
print dd.keys()
print dd['first'].keys()
印刷:
<type 'dict'>
{'second': {'name': 'test2', 'value': 50}, 'first': {'name': 'test', 'value': 100}}
['second', 'first']
['name', 'value']