summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--lib/pure/json.nim18
-rw-r--r--tests/testdata/jsonwithextradata.json6
2 files changed, 24 insertions, 0 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 5fff7352f..5e36a2aa1 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -1175,18 +1175,22 @@ when not defined(js):
   proc parseJson*(s: Stream, filename: string): JsonNode =
     ## Parses from a stream `s` into a `JsonNode`. `filename` is only needed
     ## for nice error messages.
+    ## If `s` contains extra data, it will raising `JsonParsingError`.
     var p: JsonParser
     p.open(s, filename)
     defer: p.close()
     discard getTok(p) # read first token
     result = p.parseJson()
+    eat(p, tkEof) # check there are no exstra data
 
   proc parseJson*(buffer: string): JsonNode =
     ## Parses JSON from `buffer`.
+    ## If `buffer` contains extra data, it will raising `JsonParsingError`.
     result = parseJson(newStringStream(buffer), "input")
 
   proc parseFile*(filename: string): JsonNode =
     ## Parses `file` into a `JsonNode`.
+    ## If `file` contains extra data, it will raising `JsonParsingError`.
     var stream = newFileStream(filename, fmRead)
     if stream == nil:
       raise newException(IOError, "cannot read from file: " & filename)
@@ -1412,4 +1416,18 @@ when isMainModule:
 
   doAssert escapeJson("\10FoobarÄ") == "\"\\u000AFoobar\\u00C4\""
 
+  # Test with extra data
+  when not defined(js):
+    try:
+      discard parseJson("123 456")
+      doAssert(false)
+    except JsonParsingError:
+      doAssert getCurrentExceptionMsg().contains(errorMessages[errEofExpected])
+
+    try:
+      discard parseFile("tests/testdata/jsonwithextradata.json")
+      doAssert(false)
+    except JsonParsingError:
+      doAssert getCurrentExceptionMsg().contains(errorMessages[errEofExpected])
+
   echo("Tests succeeded!")
diff --git a/tests/testdata/jsonwithextradata.json b/tests/testdata/jsonwithextradata.json
new file mode 100644
index 000000000..f6b6e7c80
--- /dev/null
+++ b/tests/testdata/jsonwithextradata.json
@@ -0,0 +1,6 @@
+{
+    "foo": 123,
+    "bar": 456
+}
+
+"foobar"