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
)
56 redef class Nvalue_object
57 redef fun to_nit_object
59 var obj
= new HashMap[String, nullable Object]
60 var members
= n_members
61 if members
!= null then
62 var pairs
= members
.pairs
63 for pair
in pairs
do obj
[pair
.name
] = pair
.value
70 fun pairs
: Array[Npair] is abstract
73 redef class Nmembers_tail
76 var arr
= n_members
.pairs
82 redef class Nmembers_head
83 redef fun pairs
do return [n_pair
]
87 fun name
: String do return n_string
.to_nit_string
88 fun value
: nullable Object do return n_value
.to_nit_object
91 redef class Nvalue_array
92 redef fun to_nit_object
94 var arr
= new Array[nullable Object]
95 var elements
= n_elements
96 if elements
!= null then
97 var items
= elements
.items
98 for item
in items
do arr
.add
(item
.to_nit_object
)
104 redef class Nelements
105 fun items
: Array[Nvalue] is abstract
108 redef class Nelements_tail
111 var items
= n_elements
.items
117 redef class Nelements_head
118 redef fun items
do return [n_value
]
122 fun json_to_nit_object
: nullable Object
124 var lexer
= new Lexer_json(self)
125 var parser
= new Parser_json
126 var tokens
= lexer
.lex
127 parser
.tokens
.add_all
(tokens
)
128 var root_node
= parser
.parse
.as(NStart)
129 return root_node
.n_0
.to_nit_object