diff --git a/src/JSON.jl b/src/JSON.jl index 66fb855..6d0b926 100644 --- a/src/JSON.jl +++ b/src/JSON.jl @@ -21,7 +21,7 @@ using .Parser: parse, parsefile using .Writer: show_json, json, lower, print, StructuralContext, show_element, show_string, show_key, show_pair, show_null, begin_array, end_array, begin_object, end_object, indent, delimit, separate, - JSONText + JSONText, printfile using .Serializations: Serialization, CommonSerialization, StandardSerialization diff --git a/src/Writer.jl b/src/Writer.jl index 6ebea04..205f201 100644 --- a/src/Writer.jl +++ b/src/Writer.jl @@ -351,6 +351,15 @@ print(io::IO, obj) = show_json(io, StandardSerialization(), obj) print(a, indent) = print(stdout, a, indent) print(a) = print(stdout, a) +""" + printfile(filename::AbstractString, printargs...) + +A convenience wrapper that opens the `filename` for writing and prints the JSON +to it. All arguments other than `filename` are forwarded to `print`. +""" +printfile(filename::AbstractString, printargs...) = + open(io -> print(io, printargs...), filename, "w") + """ json(a) json(a, indent::Int) diff --git a/test/serializer.jl b/test/serializer.jl index 87927fe..64ac1f5 100644 --- a/test/serializer.jl +++ b/test/serializer.jl @@ -85,6 +85,13 @@ let filename = tempname() rm(filename) end +# test convenience printing to file +let filename = tempname() + JSON.printfile(filename, Any[1, 2, 3.0]) + @test read(filename, String) == "[1,2,3.0]" + rm(filename) +end + # issue #184: serializing a 0-dimensional array @test sprint(JSON.show_json, JSON.StandardSerialization(), view([184], 1)) == "184"