pyparsing:示例JSON解析器无法获取字典列表 [英] pyparsing: example JSON parser fails for list of dicts
问题描述
全部
我试图了解如何使用pyparsing处理Dicts列表.我回到了示例JSON解析器最佳做法,但我发现它也无法处理所有命令列表!
I'm trying to understand how to handle a list of Dicts using pyparsing. I've gone back to the example JSON parser for best practices but I've found that it can't handle a list of dicts either!
请考虑以下内容(这是JSON解析器的示例),但是删除了一些注释,并且我的测试用例代替了默认用例):
Consider the following (this is the stock example JSON parser, but with some comments removed and my test case instead of the default one):
#!/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示例在尝试索引到第二个预期的数组元素时失败:
This is valid JSON, but the pyparsing example fails when trying to index into the second expected array element:
[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
有人可以帮助我确定此语法有什么问题吗?
Can anyone help me in identifying what's wrong with this grammar?
编辑:修复了尝试解析为JSON对象而非值的错误.
EDIT: Fixed bug in trying to parse as JSON Object, not value.
注意:这与以下内容有关: pyparsing:列表的语法字典(erlang)的地方,我基本上是想对Erlang数据结构做同样的事情,并且以类似的方式失败:(
Note: This is related to: pyparsing: grammar for list of Dictionaries (erlang) where I'm basically trying to do the same with an Erlang data structure, and failing in a similiar way :(
推荐答案
从此表达式中获得的解析结果对象是匹配标记的列表-pyparsing不知道您是否要匹配一个或多个令牌,因此它返回一个列表,如果您的列表包含1个元素,则为字典数组.
The parse results object that you get back from this expression is a list of the matched tokens - pyparsing doesn't know if you are going to match one or many tokens, so it returns a list, in your case of list containing 1 element, the array of dicts.
更改
results = jsonValue.parseString(testdata)
到
results = jsonValue.parseString(testdata)[0]
我认为情况会开始好转.完成此操作后,我得到:
and I think things will start to look better. After doing this, I get:
[0]: [['foo', 'bar'], ['baz', 'bar2']]
- baz: bar2
- foo: bar
[1]: [['foo', 'bob'], ['baz', 'fez']]
- baz: fez
- foo: bob
这篇关于pyparsing:示例JSON解析器无法获取字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!