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.

65 rivejä
1.4 KiB

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