1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 module simple_json_reader
23 fun to_nit_object
: nullable Object is abstract
26 redef class Nvalue_number
27 redef fun to_nit_object
29 var text
= n_number
.text
30 if text
.has
('.') or text
.has
('e') or text
.has
('E') then return text
.to_f
35 redef class Nvalue_string
36 redef fun to_nit_object
do return n_string
.to_nit_string
39 redef class Nvalue_true
40 redef fun to_nit_object
do return true
43 redef class Nvalue_false
44 redef fun to_nit_object
do return false
47 redef class Nvalue_null
48 redef fun to_nit_object
do return null
52 # FIXME support \n, etc.
53 fun to_nit_string
: String do return text
.substring
(1, text
.length-2
).
54 replace
("\\\\", "\\").replace
("\\\"", "\
"").replace
("\\b", "\b").
55 replace
("\\/", "/").replace
("\\n", "\n").replace
("\\r", "\r").
59 redef class Nvalue_object
60 redef fun to_nit_object
62 var obj
= new HashMap[String, nullable Object]
63 var members
= n_members
64 if members
!= null then
65 var pairs
= members
.pairs
66 for pair
in pairs
do obj
[pair
.name
] = pair
.value
73 fun pairs
: Array[Npair] is abstract
76 redef class Nmembers_tail
79 var arr
= n_members
.pairs
85 redef class Nmembers_head
86 redef fun pairs
do return [n_pair
]
90 fun name
: String do return n_string
.to_nit_string
91 fun value
: nullable Object do return n_value
.to_nit_object
94 redef class Nvalue_array
95 redef fun to_nit_object
97 var arr
= new Array[nullable Object]
98 var elements
= n_elements
99 if elements
!= null then
100 var items
= elements
.items
101 for item
in items
do arr
.add
(item
.to_nit_object
)
107 redef class Nelements
108 fun items
: Array[Nvalue] is abstract
111 redef class Nelements_tail
114 var items
= n_elements
.items
120 redef class Nelements_head
121 redef fun items
do return [n_value
]
125 fun json_to_nit_object
: nullable Object
127 var lexer
= new Lexer_json(self)
128 var parser
= new Parser_json
129 var tokens
= lexer
.lex
130 parser
.tokens
.add_all
(tokens
)
131 var root_node
= parser
.parse
.as(NStart)
132 return root_node
.n_0
.to_nit_object