V: Decoding malformed JSON doesn't fail

Created on 18 Oct 2019  路  6Comments  路  Source: vlang/v

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.

Bug Mac Confirmed

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.

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

arg2das picture arg2das  路  3Comments

PavelVozenilek picture PavelVozenilek  路  3Comments

medvednikov picture medvednikov  路  3Comments

elimisteve picture elimisteve  路  3Comments

oleg-kachan picture oleg-kachan  路  3Comments