All,
我试图了解如何使用 pyparsing 处理字典列表。我已经回到了JSON 解析器示例 http://pyparsing.wikispaces.com/file/view/jsonParser.py/30308858/jsonParser.py最佳实践,但我发现它也无法处理字典列表!
考虑以下内容(这是常用的 JSON 解析器示例,但删除了一些注释,并用我的测试用例代替了默认的测试用例):
#!/usr/bin/env python2.7
from pyparsing import *
TRUE = Keyword("true").setParseAction( replaceWith(True) )
FALSE = Keyword("false").setParseAction( replaceWith(False) )
NULL = Keyword("null").setParseAction( replaceWith(None) )
jsonString = dblQuotedString.setParseAction( removeQuotes )
jsonNumber = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) +
Optional( '.' + Word(nums) ) +
Optional( Word('eE',exact=1) + Word(nums+'+-',nums) ) )
jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
jsonArray = Group(Suppress('[') + Optional(jsonElements) + Suppress(']') )
jsonValue << ( jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL )
memberDef = Group( jsonString + Suppress(':') + jsonValue )
jsonMembers = delimitedList( memberDef )
jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )
jsonComment = cppStyleComment
jsonObject.ignore( jsonComment )
def convertNumbers(s,l,toks):
n = toks[0]
try:
return int(n)
except ValueError, ve:
return float(n)
jsonNumber.setParseAction( convertNumbers )
if __name__ == "__main__":
testdata = """
[ { "foo": "bar", "baz": "bar2" },
{ "foo": "bob", "baz": "fez" } ]
"""
results = jsonValue.parseString(testdata)
print "[0]:", results[0].dump()
print "[1]:", results[1].dump()
这是有效的 JSON,但 pyparsing 示例在尝试索引第二个预期数组元素时失败:
[0]: [[['foo', 'bar'], ['baz', 'bar2']], [['foo', 'bob'], ['baz', 'fez']]]
[1]:
Traceback (most recent call last):
File "json2.py", line 42, in <module>
print "[1]:", results[1].dump()
File "/Library/Python/2.7/site-packages/pyparsing.py", line 317, in __getitem__
return self.__toklist[i]
IndexError: list index out of range
谁能帮我找出这个语法有什么问题吗?
EDIT:修复了尝试解析为 JSON 对象而不是值时的错误。
注意:这与:pyparsing:字典列表的语法(erlang) https://stackoverflow.com/questions/22049440/pyparsing-grammar-for-list-of-dictionaries-erlang我基本上试图对 Erlang 数据结构做同样的事情,但以类似的方式失败了:(