This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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