This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

65 linhas
1.4 KiB

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