Open mcognetta opened 2 years ago
I have noticed that wrapping multiple JSON objects in [ ]
with a comma separator causes this to parse correctly:
julia> s = "[{\"name\":\"Marco\"}, {\"name\":\"Julia\"}]"
"[{\"name\":\"Marco\"}, {\"name\":\"Julia\"}]"
julia> JSON.parse(s)
2-element Vector{Any}:
Dict{String, Any}("name" => "Marco")
Dict{String, Any}("name" => "Julia")
This still leaves the problem of converting a non-delimited multiple-object JSON string to a comma separated one that can be wrapped in brackets.
Sorry, one more thing. It works if you repeatedly read from a stream:
julia> s = "{\"name\":\"Marco\"} {\"name\":\"Julia\"}"
"{\"name\":\"Marco\"} {\"name\":\"Julia\"}"
julia> stream = IOBuffer(s)
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=33, maxsize=Inf, ptr=1, mark=-1)
julia> JSON.parse(stream)
Dict{String, Any} with 1 entry:
"name" => "Marco"
julia> JSON.parse(stream)
Dict{String, Any} with 1 entry:
"name" => "Julia"
I will open a PR to add an example like this to the docs.
Some APIs that accept batch requests return a sequence of separate JSON objects that are not delimited in any way, but by parsing them you can tell they are separate as when one complete JSON object is parsed, the next non-whitespace character will start the next object
For example, you might see an string like
{"name":"Marco"} {"name":"Julia"}
, representing two distinct JSON objects.Currently, JSON.jl does not parse this correctly. It errors for the string case, and only parses the first object in the streaming case (without any indication that the stream was not exhausted).
Under the assumption that all JSON objects in the string have the same
dicttype
, I believe this can be extended to return a list of parsed objects. My first attempt is:Example:
Is this an acceptable addition to JSON.jl? One argument on its behalf is that, while a user could split the string themselves, that is basically the same as writing a JSON parser themselves, as they have to correctly handle all of the edge cases, nesting, etc in order to determine where the outermost opening and closing brackets are. Without access to the internal helper methods of JSON.jl, this is a bit of a big ask.