SHARE
TWEET

json

a guest May 16th, 2015 214 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. file: grammer.rkt
  2.  
  3.  
  4. #lang ragg
  5.  
  6. json: number | string
  7.  
  8.     | array  | object
  9.  
  10. number: NUMBER
  11.  
  12. string: STRING
  13.  
  14. array: "[" [json ("," json)*] "]"
  15.  
  16. object: "{" [kvpair ("," kvpair)*] "}"
  17.  
  18. kvpair: STRING ":" json
  19.  
  20.  
  21.  
  22. -----------------------------------------------------------
  23. file: lex.rkt
  24.  
  25. #lang racket
  26.  
  27. (require ragg/support
  28.          parser-tools/lex
  29.          "grammer.rkt"
  30.          (prefix-in : parser-tools/lex-sre))
  31.  
  32. (provide lex read-data)
  33.  
  34. (define-lex-abbrevs
  35.   [punctuator
  36.    (:or "{" "}" "[" "]" "," ":")])
  37.  
  38. (define-lex-abbrevs
  39.   [string-literal
  40.    (:: #\" (:* char-literal) #\")]
  41.  [char-literal1
  42.   (:or (:: #\\ any-char) (char-complement #\"))]
  43.  [char-literal
  44.   (:or any-char #\1)])
  45.  
  46. (define-lex-abbrevs
  47.  [number-literal
  48.   (:: int-literal
  49.       (:? frac-literal)
  50.       (:? exp-literal))]
  51.  [int-literal (:: (:? #\-) digits)]
  52.  [frac-literal (:: #\. digits)]
  53.  [exp-literal (:: e-literal digits)]
  54.  [digits (repetition 1 +inf.0 numeric)]
  55.  [e-literal (:: (:or #\e #\E) (:? (:or #\- #\+)))])
  56.      
  57.  
  58. (define lex
  59.  (lexer-src-pos
  60.   [number-literal (token 'NUMBER lexeme)]
  61.   [string-literal (token 'STRING lexeme)]
  62.   [punctuator lexeme]
  63.   [(:+ whitespace) (void)]
  64.   [(eof) (void)]))
  65.  
  66.  
  67. (define (read-data in)
  68.  (syntax->datum
  69.   (parse (λ ()
  70.            (lex in)))))
  71.  
  72.  
  73. --------------------------------------------------
  74. run this:
  75.  
  76. (require "lex.rkt")
  77.  
  78.  
  79. (define (get-jd str)
  80.  (let ([in (open-input-string str)])
  81.    (read-data in)))
  82.  
  83.  
  84. (define obj (get-jd "{\"a\":1,\"b\":2}"))
  85.  
  86. get:
  87. >obj
  88. '(json
  89.   (object
  90.    "{"
  91.    (kvpair
  92.     "\"a\":1,\"b\""
  93.     ":"
  94.     (json (number "2")))
  95.    "}"))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top