OxygenFramework / Oxygen.jl

💨 A breath of fresh air for programming web apps in Julia
https://oxygenframework.github.io/Oxygen.jl/
MIT License
383 stars 25 forks source link

json(r::HTTP.Response) not working for array of objects #119

Closed leei closed 11 months ago

leei commented 11 months ago

In handling a JSON response, there seems to be no effective way for json(HTTP.Response) to handle an "array of objects" form of response. e.g. "[{\"A\":1,\"B\":1,\"C\":1.2},{\"A\":2,\"B\":0,\"C\":1.7}]" In this case, JSON3.read() returns a JSON3.Array of JSON3.Object values and json() fails trying to convert it to a JSON3.Object

If the function signature was changed to

json(response::HTTP.Response; kwargs...) = JSON3.read(String(response.body); kwargs...)

it would all work. I'm not sure of downstream implications though...

ndortega commented 11 months ago

Hi @leei,

Not to worry, the reason for this error is that an array is a collection of JSON objects and not an object itself. To fix this issue, you just have to pass a type to the json() function to help JSON3 deserialize the underlying data. You can be as generic or as precise as you want.

json(response, Vector)

In the example below I just needed to pass a generic Vector type to the json() function to get it working.

module Main 
using Oxygen
using HTTP

# build up the sample Response
response = HTTP.Response(200, body="[{\"A\":1,\"B\":1,\"C\":1.2},{\"A\":2,\"B\":0,\"C\":1.7}]")
# convert the response to a julia object 
data = json(response, Vector)
println(data)
end

If this doesn't resolve your issue, I'd ask that you copy & paste an example of your code so I have more context.