gpt4 book ai didi

python - pyparsing:示例 JSON 解析器对于字典列表失败

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:53 26 4
gpt4 key购买 nike

全部,

我正在尝试了解如何使用 pyparsing 处理字典列表。我已经回到 example JSON parser 以获得最佳实践,但我发现它也无法处理字典列表!

考虑以下内容(这是常见的 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

谁能帮我确定这个语法有什么问题?

编辑:修复了尝试解析为 JSON 对象而非值时的错误。

注意:这与:pyparsing: grammar for list of Dictionaries (erlang) 有关,我基本上是在尝试对 Erlang 数据结构做同样的事情,但以类似的方式失败了:(

最佳答案

这可能是 valid JSON ,但你的语法不会处理它。原因如下:

jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )

这表示语法对象必须被{...}包围。您将其作为数组 [...] 来支撑。由于顶级对象必须是字典,因此它需要键名。将您的测试数据更改为:

{ "col1":{ "foo": "bar", "baz": "bar2" },
"col2":{ "foo": "bob", "baz": "fez" } }

{ "data":[{ "foo": "bar", "baz": "bar2" },
{ "foo": "bob", "baz": "fez" }] }

将允许此语法 对其进行解析。想要一个顶级对象是一个数组?修改语法即可!

关于python - pyparsing:示例 JSON 解析器对于字典列表失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22081239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com