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.

79 lines
1.9 KiB

  1. #
  2. # This example shows how to write a basic 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. #
  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].replace('\\"', '"')
  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='earley', lexer='standard')
  39. # def parse(x):
  40. # return TreeToJson().transform(json_parser.parse(x))
  41. json_parser = Lark(json_grammar, parser='lalr', transformer=TreeToJson())
  42. parse = json_parser.parse
  43. def test():
  44. test_json = '''
  45. {
  46. "empty_object" : {},
  47. "empty_array" : [],
  48. "booleans" : { "YES" : true, "NO" : false },
  49. "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
  50. "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ],
  51. "nothing" : null
  52. }
  53. '''
  54. j = parse(test_json)
  55. print(j)
  56. import json
  57. assert j == json.loads(test_json)
  58. if __name__ == '__main__':
  59. # test()
  60. with open(sys.argv[1]) as f:
  61. print(parse(f.read()))