Last active
June 15, 2022 22:43
-
-
Save trim21/de6301a1aecc0756d50c712648559c83 to your computer and use it in GitHub Desktop.
python parse php var_dump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
parse a PHP `var_dump` string to a python dict | |
Copy Right 2021 Trim21<trim21.me@gmail.com> | |
Licensed under MIT License | |
https://spdx.org/licenses/MIT.html | |
""" | |
import pyparsing as pp | |
identify = pp.Word(pp.alphas + "_") | |
indent = pp.Suppress(pp.ZeroOrMore(" ")) | |
key_to = pp.Suppress("[") + identify + pp.Suppress("]") + pp.Suppress("=>") + pp.Suppress(pp.ZeroOrMore(' ')) | |
key_value = key_to + pp.restOfLine | |
def parse(s: str): | |
data = {} | |
_data = data | |
stack = [] | |
for line in s.splitlines(): | |
if not line: | |
continue | |
if line == '(': | |
continue | |
if line == ')': | |
*stack, _data = stack | |
continue | |
key, value = key_value.parseString(line) | |
if value != 'Array': | |
_data[key] = value or None | |
else: | |
stack.append(_data) | |
_data = {} | |
stack[-1][key] = _data | |
return data | |
if __name__ == '__main__': | |
raw = """[TID] => 535 | |
[a] => 0.250 | |
[b] => Array | |
( | |
[c] => 0 B | |
[d] => | |
) | |
[e] => 0.5""" | |
print(parse(raw)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment