我正在尝试将类似JSON的简单结构解析为python dics,然后将其转换为适当的JSON结构。该块如下:
###################################################
# HEADER TEXT
# HEADER TEXT
###################################################
NAME => {
NAME => VALUE,
NAME => VALUE,
NAME => VALUE,
NAME => {
NAME => {
NAME => VALUE, NAME => VALUE, NAME => VALUE,
},
} # comment
}, # more comments
并重复。规则:
NAME = alphanums and _
VALUE = decimal(6) | hex (0xA) | list of hex ([0x1,0x2]) | text in brackets([A]) | string("A")
我设置了以下语法:
cfgName = Word(alphanums+"_")
cfgString = dblQuotedString().setParseAction(removeQuotes)
cfgNumber = Word("0123456789ABCDEFx")
LBRACK, RBRACK, LBRACE, RBRACE = map(Suppress, "[]{}")
EQUAL = Literal('=>').suppress()
cfgObject = Forward()
cfgValue = Forward()
cfgElements = delimitedList(cfgValue)
cfgArray = Group(LBRACK + Optional(cfgElements, []) + RBRACK)
cfgValue << (cfgString | cfgNumber | cfgArray | cfgName | Group(cfgObject))
memberDef = Group(cfgName + EQUAL + cfgValue)
cfgMembers = delimitedList(memberDef)
cfgObject << Dict(LBRACE + Optional(cfgMembers) + RBRACE)
cfgComment = pythonStyleComment
cfgObject.ignore(cfgComment)
编辑:我设法解决了这个问题。正确的JSON是
{member,member,member}
但我的结构是:
{member,member,member,}
每个嵌套结构中的最后一个元素都是逗号分隔的,我不知道如何在语法中考虑它。