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
20 private import json_parser
21 private import json_lexer
24 fun to_nit_object
: nullable Object is abstract
27 redef class Nvalue_number
28 redef fun to_nit_object
30 var text
= n_number
.text
31 if text
.chars
.has
('.') or text
.chars
.has
('e') or text
.chars
.has
('E') then return text
.to_f
36 redef class Nvalue_string
37 redef fun to_nit_object
do return n_string
.to_nit_string
40 redef class Nvalue_true
41 redef fun to_nit_object
do return true
44 redef class Nvalue_false
45 redef fun to_nit_object
do return false
48 redef class Nvalue_null
49 redef fun to_nit_object
do return null
53 # FIXME support \n, etc.
54 fun to_nit_string
: String do return text
.substring
(1, text
.length-2
).
55 replace
("\\\\", "\\").replace
("\\\"", "\
"").replace
("\\b", "\b").
56 replace
("\\/", "/").replace
("\\n", "\n").replace
("\\r", "\r").
60 redef class Nvalue_object
61 redef fun to_nit_object
63 var obj
= new HashMap[String, nullable Object]
64 var members
= n_members
65 if members
!= null then
66 var pairs
= members
.pairs
67 for pair
in pairs
do obj
[pair
.name
] = pair
.value
74 fun pairs
: Array[Npair] is abstract
77 redef class Nmembers_tail
80 var arr
= n_members
.pairs
86 redef class Nmembers_head
87 redef fun pairs
do return [n_pair
]
91 fun name
: String do return n_string
.to_nit_string
92 fun value
: nullable Object do return n_value
.to_nit_object
95 redef class Nvalue_array
96 redef fun to_nit_object
98 var arr
= new Array[nullable Object]
99 var elements
= n_elements
100 if elements
!= null then
101 var items
= elements
.items
102 for item
in items
do arr
.add
(item
.to_nit_object
)
108 redef class Nelements
109 fun items
: Array[Nvalue] is abstract
112 redef class Nelements_tail
115 var items
= n_elements
.items
121 redef class Nelements_head
122 redef fun items
do return [n_value
]
126 fun json_to_nit_object
: nullable Object
128 var lexer
= new Lexer_json(self)
129 var parser
= new Parser_json
130 var tokens
= lexer
.lex
131 parser
.tokens
.add_all
(tokens
)
132 var root_node
= parser
.parse
133 if root_node
isa NStart then
134 return root_node
.n_0
.to_nit_object
136 assert root_node
isa NLexerError
137 var pos
= root_node
.position
138 print
"Json parsing error: {root_node.message} at {pos or else "<unknown>"} for {root_node}"