在aws api网关中,我想通过api网关将整个查询字符串传递给kinesis,
#set($querystring = $input.params().querystring)
"Data": "$util.base64Encode($querystring)"
但是从kinesis记录中获取的数据看起来像'{tracker_name = xxxx,tracker = yyyy}',这不是json字符串格式,所以我需要特别注意这个奇怪的字符串,使其成为aws中的json字符串lambda(Python引擎)。有什么好主意吗?
答案 0 :(得分:1)
我不熟悉AWS API网关,但专注于字符串格式化问题,编写一个简单的解析器将其转换为您想要的任何其他格式并不难。
至于你的描述,我写了一个简单的Python解析器,希望它可以给你一些想法。
class MyParser:
def __init__(self, source):
# the source string
self.source = source
# current position
self.at = 0
# current character
self.ch = source[0] if len(source) > 0 else ''
def error(self, msg):
'''Print an error message and raise an exception'''
print '-- Parser abort due to a fatal error: \n-- %s' % msg
raise ValueError()
def check_char(self, expected):
'''
Check if current character is same as the given character.
If not, raise an exception.
'''
if self.at >= len(self.source):
self.error('At position %d: %c expected, but reached string end' % (self.at, expected))
elif self.ch != expected:
self.error('At position %d: %c expected, but %c given' % (self.at, expected, self.ch))
def next_char(self):
'''Move on to next character in source string.'''
self.at += 1
self.ch = self.source[self.at] if len(self.source) > self.at else ''
return self.ch
def eat_spaces(self):
'''Eat up white spaces.'''
while self.ch == ' ':
self.next_char()
def parse_string(self):
'''Parse a string value.'''
s = ''
while self.ch != '=' and self.ch != ',' and self.ch != '}' and self.at < len(self.source):
s += self.ch
self.next_char()
return s.strip()
def parse_object(self):
'''Parse an object value.'''
obj = {}
# eat '{'
self.next_char()
self.eat_spaces()
while self.ch != '}':
if self.at >= len(self.source):
self.error('Malformed source string')
key = self.parse_string()
# eat '='
self.check_char('=')
self.next_char()
val = self.parse_value()
obj[key] = val
# eat ','
if self.ch == ',':
self.next_char()
self.eat_spaces()
# eat '}'
self.next_char()
return obj
def parse_value(self):
'''Parse a value.'''
self.eat_spaces()
if self.ch == '{':
return self.parse_object()
else:
return self.parse_string()
def parse(self):
'''Let the game begin.'''
self.eat_spaces()
if self.ch != '{':
self.error('Source string must begin with \'{\'')
else:
return self.parse_value()
使用它:
MyParser('{tracker_name=xxxx, tracker=yyyy}').parse()