【发布时间】:2014-03-31 15:12:07
【问题描述】:
全部,
我正在尝试了解如何使用 pyparsing 处理字典列表。我已经回到example JSON parser 以获得最佳实践,但我发现它也无法处理字典列表!
考虑以下内容(这是常用的 JSON 解析器示例,但删除了一些 cmets 和我的测试用例,而不是默认用例):
#!/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
谁能帮我找出这个语法有什么问题?
编辑:修复了尝试解析为 JSON 对象而不是值时的错误。
注意:这与:pyparsing: grammar for list of Dictionaries (erlang) 相关,我基本上是在尝试对 Erlang 数据结构做同样的事情,但以类似的方式失败:(
【问题讨论】:
标签: python json parsing pyparsing