使用pyparsing解析JSON之类的格式

时间:2017-05-23 20:03:18

标签: python pyparsing

关于解析数据格式等JSON,我有两个相关的问题 使用pyparsing目标是解析此数据并转换 结果为JSON。

1)第一种类型的数据类似于

mystr = """
    DataName = {
        fieldA = {
            fieldB = 10
            fieldC = "absf"
        }
    }
    DataName = {
        fieldA = {
            fieldB = 11
            fieldC = "bsf"
        }
    }
"""

我想知道按顺序设置语法的最佳方法是什么 将mystr解析为类似于

的字典列表
expected_result = [{"DataName": {"fieldA": {"fieldB": 10, "fieldC": "absf"}}},
                   {"DataName": {"fieldA": {"fieldB": 11, "fieldC": "bsf"}}}]

我的第一次尝试如下

from pyparsing import *
LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas + '[]')
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()

value = (string | number)
jobject = Forward()
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef ^ jobject, delim=LineEnd())
jobject << Dict(field + EQUAL + LBRACE + Optional(members) + RBRACE)

members.parseString(mystr)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-70cbdee9640b> in <module>()
----> 1 members.parseString(mystr)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseString(self, instring, parseAll)
   1204             instring = instring.expandtabs()
   1205         try:
-> 1206             loc, tokens = self._parse( instring, 0 )
   1207             if parseAll:
   1208                 loc = self.preParse( instring, loc )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2525         # pass False as last arg to _parse for first element, since we already
   2526         # pre-parsed the string as part of our And pre-parsing
-> 2527         loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
   2528         errorStop = False
   2529         for e in self.exprs[1:]:

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2587         for e in self.exprs:
   2588             try:
-> 2589                 loc2 = e.tryParse( instring, loc )
   2590             except ParseException as err:
   2591                 err.__traceback__ = None

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in tryParse(self, instring, loc)
   1112     def tryParse( self, instring, loc ):
   1113         try:
-> 1114             return self._parse( instring, loc, doActions=False )[0]
   1115         except ParseFatalException:
   1116             raise ParseException( instring, loc, self.errmsg, self)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2799     def parseImpl( self, instring, loc, doActions=True ):
   2800         if self.expr is not None:
-> 2801             return self.expr._parse( instring, loc, doActions, callPreParse=False )
   2802         else:
   2803             raise ParseException("",loc,self.errmsg,self)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2799     def parseImpl( self, instring, loc, doActions=True ):
   2800         if self.expr is not None:
-> 2801             return self.expr._parse( instring, loc, doActions, callPreParse=False )
   2802         else:
   2803             raise ParseException("",loc,self.errmsg,self)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2542                     raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
   2543             else:
-> 2544                 loc, exprtokens = e._parse( instring, loc, doActions )
   2545             if exprtokens or exprtokens.haskeys():
   2546                 resultlist += exprtokens

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   3004     def parseImpl( self, instring, loc, doActions=True ):
   3005         try:
-> 3006             loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
   3007         except (ParseException,IndexError):
   3008             if self.defaultValue is not _optionalNotMatched:

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2525         # pass False as last arg to _parse for first element, since we already
   2526         # pre-parsed the string as part of our And pre-parsing
-> 2527         loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
   2528         errorStop = False
   2529         for e in self.exprs[1:]:

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2587         for e in self.exprs:
   2588             try:
-> 2589                 loc2 = e.tryParse( instring, loc )
   2590             except ParseException as err:
   2591                 err.__traceback__ = None

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in tryParse(self, instring, loc)
   1112     def tryParse( self, instring, loc ):
   1113         try:
-> 1114             return self._parse( instring, loc, doActions=False )[0]
   1115         except ParseFatalException:
   1116             raise ParseException( instring, loc, self.errmsg, self)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1070             if self.mayIndexError or loc >= len(instring):
   1071                 try:
-> 1072                     loc,tokens = self.parseImpl( instring, preloc, doActions )
   1073                 except IndexError:
   1074                     raise ParseException( instring, len(instring), self.errmsg, self )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in parseImpl(self, instring, loc, doActions)
   2799     def parseImpl( self, instring, loc, doActions=True ):
   2800         if self.expr is not None:
-> 2801             return self.expr._parse( instring, loc, doActions, callPreParse=False )
   2802         else:
   2803             raise ParseException("",loc,self.errmsg,self)

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in _parseNoCache(self, instring, loc, doActions, callPreParse)
   1076                 loc,tokens = self.parseImpl( instring, preloc, doActions )
   1077
-> 1078         tokens = self.postParse( instring, loc, tokens )
   1079
   1080         retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )

/home/matthew/anaconda3/lib/python3.5/site-packages/pyparsing.py in postParse(self, instring, loc, tokenlist)
   3247                 tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
   3248             else:
-> 3249                 dictvalue = tok.copy() #ParseResults(i)
   3250                 del dictvalue[0]
   3251                 if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.haskeys()):

AttributeError: 'str' object has no attribute 'copy'

这不起作用,但我不明白为什么。 mystrdelimitedList 两个jobject s(DataName s),其中每个jobject包含1个jobjectfieldA)由1 members组成,其中包含两个memberDefs。 我在这里缺少什么?

或者,我可以按如下方式定义我的语法

value = Forward()
jobject = Forward()
value << (string | number | Group(jobject))
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members) + RBRACE)
res = members.parseString(mystr)

然后我可以遍历结果并生成字典,但是这样 感觉像是一块垃圾。

list_of_dicts = []
for pair in res:
    list_of_dicts.append({pair[0]: pair[1].asDict()})

print(list_of_dicts)
[{'DataName': {'fieldA': {'fieldC': 'absf', 'fieldB': 10.0}}}, {'DataName': {'fieldA': {'fieldC': 'bsf', 'fieldB': 11.0}}}]

2)数据格式还包括以下文字。

mystr2 = """
fieldA = {
    someFieldA[] = {
    }
    someFieldB[] = {
        "typeA", "typeB"
    }
    someFieldC[] = {
        fieldData = {
            data = 10
        }
        fieldData = {
            data = 12
        }
    }
    someFieldD = "bsf"
}
fieldA = {
}
"""

我想将其解析为字典列表,如下所示

expected_result2 = [{"fieldA": {"someFieldA": [],
                               "someFieldB": ["typeA", "typeB"],
                               "someFieldC":[{"fieldData": {"data": 10}},
                                             {"fieldData": {"data": 10}}],
                               "someFieldD": "bsf"}},
                    {"fieldA": {}}]

我试图通过在语法

中添加array类型来解决这个问题
value = Forward()
jobject = Forward()

arrayElements = delimitedList(string)
array = Group(LBRACE + Optional(arrayElements, []) + RBRACE)

value << (string | number | Group(jobject) | array)
memberDef = Group(field + EQUAL + value)
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members) + RBRACE)

res2 = members.parseString(mystr2)
print(res2)
 [['fieldA', [['someFieldA[]', []], ['someFieldB', ['typeA', 'typeB']], ['someFieldC[]', [['fieldData', [['data', 10.0]]], ['fieldData', [['data', 12.0]]]]], ['someFieldD', 'bsf']]], ['fieldA', []]]

这会返回一个parseResult但是我不确定如何进行转换 就像expected_result2之类的东西。另外,上面的语法中没有任何内容可以区分形式的元素

Data = {
}

Data[] = {
}

应分别映射到{"Data": {}}{"Data": []}

修改

上面的mystr2中有一个拼写错误,someFieldB[] = {被错误地写为someFieldB = {

考虑[]重要性的语法如下所示。

LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas)
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()
scalar_value = (string | number)

value_list = Forward()
jobject = Forward()

memberDef1 = Group(field + EQUAL + scalar_value)
memberDef2 = Group(field + EQUAL + jobject)
memberDef3 = Group(field + "[]" + EQUAL + LBRACE + value_list + RBRACE)
memberDef = memberDef1 | memberDef2 | memberDef3

value_list << (delimitedList(string, ",") | ZeroOrMore(memberDef2))
members = delimitedList(memberDef, delim=LineEnd())
jobject << Dict(LBRACE + Optional(members, '{}') + RBRACE)
res = members.parseString(mystr2)

似乎正在解析,但是我仍然不清楚如何将res转换为词典列表?

编辑2

下面列出了说明语法的实际例子

HistoricalDataRequest = {
    securities[] = {
        "SPY US Equity", "TLT US Equity"
    }
    fields[] = {
        "PX_LAST"
    }
    startDate = "20150629"
    endDate = "20150630"
    overrides[] = {
    }
}

HistoricalDataResponse = {
    securityData = {
        security = "SPY US Equity"
        eidData[] = {
        }
        sequenceNumber = 0
        fieldExceptions[] = {
        }
        fieldData[] = {
            fieldData = {
                date = 2015-06-29
                PX_LAST = 205.420000
            }
            fieldData = {
                date = 2015-06-30
                PX_LAST = 205.850000
            }
        }
    }
}

HistoricalDataResponse = {
    securityData = {
        security = "TLT US Equity"
        eidData[] = {
        }
        sequenceNumber = 1
        fieldExceptions[] = {
        }
        fieldData[] = {
            fieldData = {
                date = 2015-06-29
                PX_LAST = 118.280000
            }
            fieldData = {
                date = 2015-06-30
                PX_LAST = 117.460000
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

好的,有一些finagling和shenanigans,我想我已经设计了一个解析器,它可以为你提供这种格式的JSON-dicts。

LBRACE, RBRACE, EQUAL = map(Suppress, "{}=")
field = Word(alphas, alphas+'_')
# was field = Word(alphas)
string = dblQuotedString().setParseAction(removeQuotes)
number = pyparsing_common.number()
date_expr = Regex(r'\d\d\d\d-\d\d-\d\d')
scalar_value = (string | date_expr | number)
# was scalar_value = (string | number)

list_marker = Suppress("[]")
value_list = Forward()
jobject = Forward()

memberDef1 = Group(field + EQUAL + scalar_value)
memberDef2 = Group(field + EQUAL + jobject)
memberDef3 = Group(field + list_marker + EQUAL + LBRACE + value_list + RBRACE)
memberDef = memberDef1 | memberDef2 | memberDef3

value_list <<= (delimitedList(scalar_value, ",") | ZeroOrMore(Group(Dict(memberDef2))))
value_list.setParseAction(lambda t: [ParseResults(t[:])])

members = OneOrMore(memberDef)
jobject <<= Dict(LBRACE + ZeroOrMore(memberDef) + RBRACE)
# force empty jobject to be a dict
jobject.setParseAction(lambda t: t or {})

parser = members
parser = OneOrMore(Group(Dict(memberDef)))

tests = [mystr, mystr2]

import pprint
import json
for test in tests:
    print(test)
    res = parser.parseString(test)
    for res_dict in res:
        pprint.pprint(res_dict.asDict())
        # or convert to JSON using:
        # print(json.dumps(res_dict.asDict(), indent=2))
    print('')

打印(为jobject添加空someFieldE,为someFieldF添加空列表:

{'DataName': {'fieldA': {'fieldB': 10, 'fieldC': 'absf'}}}
{'DataName': {'fieldA': {'fieldB': 11, 'fieldC': 'bsf'}}}

{'fieldA': {'someFieldA': [],
            'someFieldB': ['typeA', 'typeB'],
            'someFieldC': [{'a': {'data': 10}}, {'a': {'data': 12}}],
            'someFieldD': 'bsf',
            'someFieldE': {},
            'someFieldF': []}}

我使用围绕Group的{​​{1}}处理多个dict密钥,以便将重复密钥隔离到单独的Dict中。 ParseResults上的解析操作就是这样,空列表在列表中返回空value_list。我必须强制空ParseResults s成为dicts,因为将它们留空jobject将没有任何键,因此不会从ParseResults返回一个字典。

(编辑:为了适应您发布的示例,我必须添加&#39; _&#39;作为有效的字段名称字符,并为类似日期的字段值定义新的asDict()类型。 )