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.

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