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.

76 lines
1.6 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. | number
  15. | "true" -> true
  16. | "false" -> false
  17. | "null" -> null
  18. array : "[" [value ("," value)*] "]"
  19. object : "{" [pair ("," pair)*] "}"
  20. pair : string ":" value
  21. number: FLOAT
  22. string : ESCAPED_STRING
  23. %import common.ESCAPED_STRING
  24. %import common.FLOAT
  25. %import common.WS
  26. %ignore WS
  27. """
  28. class TreeToJson(Transformer):
  29. @inline_args
  30. def string(self, s):
  31. return s[1:-1]
  32. array = list
  33. pair = tuple
  34. object = dict
  35. number = inline_args(float)
  36. null = lambda self, _: None
  37. true = lambda self, _: True
  38. false = lambda self, _: False
  39. json_parser = Lark(json_grammar, parser='lalr', transformer=TreeToJson())
  40. parse = json_parser.parse
  41. def test():
  42. test_json = '''
  43. {
  44. "empty_object" : {},
  45. "empty_array" : [],
  46. "booleans" : { "YES" : true, "NO" : false },
  47. "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
  48. "strings" : [ "This", [ "And" , "That" ] ],
  49. "nothing" : null
  50. }
  51. '''
  52. j = parse(test_json)
  53. print(j)
  54. import json
  55. assert j == json.loads(test_json)
  56. if __name__ == '__main__':
  57. test()
  58. with open(sys.argv[1]) as f:
  59. print(parse(f.read()))