2
* Copyright (C) 2009-2011 Mathias Doenitz
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
17
package org.parboiled.examples.json
19
import org.testng.annotations.Test
20
import org.scalatest.testng.TestNGSuite
21
import org.testng.Assert.assertEquals
22
import org.parboiled.scala.testing.ParboiledTest
23
import org.parboiled.scala.parserunners.ReportingParseRunner
25
class JsonParserTest extends ParboiledTest with TestNGSuite {
26
val parser = new JsonParser1()
28
type Result = parser.AstNode
31
def testJsonParser() {
33
| "simpleKey" : "some value",
34
| "key with spaces": null,
36
| "number": -1.2323424E-5,
38
| "Boolean no": false,
39
| "Unic\u00f8de" : "Long string with newline\nescape",
40
| "key with \"quotes\"" : "string",
44
| "array": [1, 2, { "yes":1, "no":0 }, ["a", "b", null], false]
48
val rootNode = parser.parseJson(json)
49
assertEquals(printAst(rootNode),
51
| "simpleKey" : "some value"
52
| "key with spaces" : null
54
| "number" : -0.000012323424
55
| "Boolean yes" : true
56
| "Boolean no" : false
57
| "Unicøde" : "Long string with newline\nescape"
58
| "key with \"quotes\"" : "string"
65
| }, ["a", "b", null], false]
71
def testJsonParserError() {
72
failParse(ReportingParseRunner(parser.Json), "XYZ") {
74
"""|Invalid input 'X', expected Json (line 1, pos 1):
82
def printAst(node: JsonParser1#AstNode, indent: String = ""): String = node match {
83
case n: JsonParser1#ObjectNode => "{\n" + (for (sub <- n.members) yield printAst(sub, indent + " ")).mkString + indent + "}"
84
case n: JsonParser1#MemberNode => indent + '"' + n.key + "\" : " + printAst(n.value, indent) + "\n"
85
case n: JsonParser1#ArrayNode => '[' + (for (sub <- n.elements) yield printAst(sub, indent + " ")).mkString(", ") + "]"
86
case n: JsonParser1#StringNode => '"' + n.text + '"'
87
case n: JsonParser1#NumberNode => n.value.toString
88
case parser.True => "true"
89
case parser.False => "false"
90
case parser.Null => "null"
b'\\ No newline at end of file'