V version: V 0.1.21 6890034
OS: macOS
What did you do?
Parsing something that clearly wasn't JSON, onto a struct with string fields.
What did you expect to see?
json.decode() calling its or block.
What did you see instead?
json.decode() returned the struct with empty string fields.
Please post a minimal working example. This allows people to test the situation easily and to make sure everyone is talking about the same.
~ cat demo.txt
"foo"
import json
import os
struct Demo {
name string
}
fn main() {
json_str := os.read_file("demo.txt") or { panic(err) }
demo := json.decode(Demo, json_str) or { panic(err) }
println(demo.name)
}
I would expect this to panic. But it prints an empty string.
Thank you very much for your example. I can confirm that this prints an empty string here too. I want to note that this is valid JSON. The problem is that it does not fit in the Demo struct. I am not entirely sure whether this is unexpected behaviour.
Making this panic, would mean that you can't use optional JSON keys in your struct for example.
I agree. How about having [required] JSON fields, similar to the existing [skip]?
I think we need a whole new JSON library that automatically decodes the JSON, instead of you having to define the structs in advance. If that's not an option, I wouldn't see a problem in creating [required].
I think we need a whole new JSON library that automatically decodes the JSON, instead of you having to define the structs in advance. If that's not an option, I wouldn't see a problem in creating
[required].
I won't be closing this issue since it still persists but I would like to point out that we have a new JSON library that does that: https://modules.vlang.io/x.json2.html
Most helpful comment
Please post a minimal working example. This allows people to test the situation easily and to make sure everyone is talking about the same.