This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

65 рядки
1.7 KiB

  1. """
  2. Simple JSON Parser
  3. ==================
  4. The code is short and clear, and outperforms every other parser (that's written in Python).
  5. For an explanation, check out the JSON parser tutorial at /docs/json_tutorial.md
  6. (this is here for use by the other examples)
  7. """
  8. import sys
  9. from lark import Lark, Transformer, v_args
  10. json_grammar = r"""
  11. ?start: value
  12. ?value: object
  13. | array
  14. | string
  15. | SIGNED_NUMBER -> number
  16. | "true" -> true
  17. | "false" -> false
  18. | "null" -> null
  19. array : "[" [value ("," value)*] "]"
  20. object : "{" [pair ("," pair)*] "}"
  21. pair : string ":" value
  22. string : ESCAPED_STRING
  23. %import common.ESCAPED_STRING
  24. %import common.SIGNED_NUMBER
  25. %import common.WS
  26. %ignore WS
  27. """
  28. class TreeToJson(Transformer):
  29. @v_args(inline=True)
  30. def string(self, s):
  31. return s[1:-1].replace('\\"', '"')
  32. array = list
  33. pair = tuple
  34. object = dict
  35. number = v_args(inline=True)(float)
  36. null = lambda self, _: None
  37. true = lambda self, _: True
  38. false = lambda self, _: False
  39. ### Create the JSON parser with Lark, using the LALR algorithm
  40. json_parser = Lark(json_grammar, parser='lalr',
  41. # Using the standard lexer isn't required, and isn't usually recommended.
  42. # But, it's good enough for JSON, and it's slightly faster.
  43. lexer='standard',
  44. # Disabling propagate_positions and placeholders slightly improves speed
  45. propagate_positions=False,
  46. maybe_placeholders=False,
  47. # Using an internal transformer is faster and more memory efficient
  48. transformer=TreeToJson())