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.
 
 

63 lines
1.4 KiB

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