parent
da1293c405
commit
abe5cb82a0
2 changed files with 24 additions and 0 deletions
|
|
@ -1175,18 +1175,22 @@ when not defined(js):
|
||||||
proc parseJson*(s: Stream, filename: string): JsonNode =
|
proc parseJson*(s: Stream, filename: string): JsonNode =
|
||||||
## Parses from a stream `s` into a `JsonNode`. `filename` is only needed
|
## Parses from a stream `s` into a `JsonNode`. `filename` is only needed
|
||||||
## for nice error messages.
|
## for nice error messages.
|
||||||
|
## If `s` contains extra data, it will raising `JsonParsingError`.
|
||||||
var p: JsonParser
|
var p: JsonParser
|
||||||
p.open(s, filename)
|
p.open(s, filename)
|
||||||
defer: p.close()
|
defer: p.close()
|
||||||
discard getTok(p) # read first token
|
discard getTok(p) # read first token
|
||||||
result = p.parseJson()
|
result = p.parseJson()
|
||||||
|
eat(p, tkEof) # check there are no exstra data
|
||||||
|
|
||||||
proc parseJson*(buffer: string): JsonNode =
|
proc parseJson*(buffer: string): JsonNode =
|
||||||
## Parses JSON from `buffer`.
|
## Parses JSON from `buffer`.
|
||||||
|
## If `buffer` contains extra data, it will raising `JsonParsingError`.
|
||||||
result = parseJson(newStringStream(buffer), "input")
|
result = parseJson(newStringStream(buffer), "input")
|
||||||
|
|
||||||
proc parseFile*(filename: string): JsonNode =
|
proc parseFile*(filename: string): JsonNode =
|
||||||
## Parses `file` into a `JsonNode`.
|
## Parses `file` into a `JsonNode`.
|
||||||
|
## If `file` contains extra data, it will raising `JsonParsingError`.
|
||||||
var stream = newFileStream(filename, fmRead)
|
var stream = newFileStream(filename, fmRead)
|
||||||
if stream == nil:
|
if stream == nil:
|
||||||
raise newException(IOError, "cannot read from file: " & filename)
|
raise newException(IOError, "cannot read from file: " & filename)
|
||||||
|
|
@ -1412,4 +1416,18 @@ when isMainModule:
|
||||||
|
|
||||||
doAssert escapeJson("\10FoobarÄ") == "\"\\u000AFoobar\\u00C4\""
|
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!")
|
echo("Tests succeeded!")
|
||||||
|
|
|
||||||
6
tests/testdata/jsonwithextradata.json
vendored
Normal file
6
tests/testdata/jsonwithextradata.json
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"foo": 123,
|
||||||
|
"bar": 456
|
||||||
|
}
|
||||||
|
|
||||||
|
"foobar"
|
||||||
Loading…
Add table
Add a link
Reference in a new issue