This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.7 KiB

  1. #
  2. # This example shows how to write a basic JSON parser
  3. #
  4. # The code is short and clear, but has good performance.
  5. # For an explanation, check out the JSON parser tutorial at /docs/json_tutorial.md
  6. #
  7. import sys
  8. from lark import Lark, inline_args, Transformer
  9. json_grammar = r"""
  10. ?start: value
  11. ?value: object
  12. | array
  13. | string
  14. | SIGNED_NUMBER -> number
  15. | "true" -> true
  16. | "false" -> false
  17. | "null" -> null
  18. array : "[" [value ("," value)*] "]"
  19. object : "{" [pair ("," pair)*] "}"
  20. pair : string ":" value
  21. string : ESCAPED_STRING
  22. %import common.ESCAPED_STRING
  23. %import common.SIGNED_NUMBER
  24. %import common.WS
  25. %ignore WS
  26. """
  27. class TreeToJson(Transformer):
  28. @inline_args
  29. def string(self, s):
  30. return s[1:-1]
  31. array = list
  32. pair = tuple
  33. object = dict
  34. number = inline_args(float)
  35. null = lambda self, _: None
  36. true = lambda self, _: True
  37. false = lambda self, _: False
  38. json_parser = Lark(json_grammar, parser='lalr', transformer=TreeToJson())
  39. parse = json_parser.parse
  40. def test():
  41. test_json = '''
  42. {
  43. "empty_object" : {},
  44. "empty_array" : [],
  45. "booleans" : { "YES" : true, "NO" : false },
  46. "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
  47. "strings" : [ "This", [ "And" , "That" ] ],
  48. "nothing" : null
  49. }
  50. '''
  51. j = parse(test_json)
  52. print(j)
  53. import json
  54. assert j == json.loads(test_json)
  55. if __name__ == '__main__':
  56. test()
  57. with open(sys.argv[1]) as f:
  58. print(parse(f.read()))