JSON3 Package: ArgumentError: invalid JSON at byte .... : InvalidChar?

There are two issues in the code you are using

  • JSON3.Struct() passes the arguments by order meaning it would tries to parse id_str as a id::Union{Int64, Nothing} which gives the error as it tries to
parse(Int64, "\"1305501948074835974\"")
  • You are missing the StructType(::Type{User}) declaration

The way to fix it, especially using Twitter data, is to use Mutable like this:

using JSON3: JSON3, StructType, Mutable
using Dates: DateTime, DateFormat
import Base: show, summary
mutable struct User
    id :: UInt64
    name :: String
    created_at :: DateTime
    User() = new()
end
mutable struct Status
    id :: UInt64
    user :: User
    created_at :: DateTime
    place :: Union{Missing, String}
    Status() = new()
end
summary(io::IO, obj::Status) = print(io, "Twitter Status: $(obj.id)")
function show(io::IO, obj::Status)
    println(io, summary(obj))
    println(io, "  User: $(obj.user.name)")
    println(io, "  On: $(obj.created_at)")
end
StructType(::Type{User}) = Mutable()
StructType(::Type{Status}) = Mutable()
json_str = "{\"id_str\":\"1305501948074835974\",\"created_at\":\"Mon Sep 14 13:41:34 +0000 2020\",\"place\":null,\"id\":1305501948074835974,\"user\":{\"name\":\"Donald J. Trump\",\"id_str\":\"25073877\",\"created_at\":\"Wed Mar 18 13:46:38 +0000 2009\",\"id\":25073877}}"
JSON3.read(json_str, Status, dateformat = DateFormat("e u dd HH:MM:SS +0000 yyyy"))
3 Likes