V: Built in JSON panics on empty json property

Created on 31 May 2020  路  2Comments  路  Source: vlang/v

V version:
V 0.1.27 3a36ed3

OS:
Ubuntu 20,x
What did you do?
I was building a test to decode json messages. See code below

struct HassMessage {
    pub:

    id              int
    message_type    string [json:'type']
    hass_event      string [raw; json:'event']
    result          string [raw]

// Parse the message type from Home Assistant messagwe
fn parse_hass_message(jsn string) ?HassMessage {
    hass_message := json.decode(HassMessage, jsn) or {return error(err)}
    return hass_message
}

// Test method
fn test_parse_message_type_minimal_returns_correct_type() {
    hass_msg := hassclient.parse_hass_message('{"type": "testtype", "event": {"hello": "world"}') or {exit(1)}
    print(hass_msg)

        //assert hass_msg.message_type == 'testtype'
    assert false // Just to get the print
}


What did you expect to see?
Expectred to see successfull parsed object with result == ''

What did you see instead?

AIL  966.488 ms hassclient/messages_test.v
V panic: tos2: nil string
Bug

Most helpful comment

it fails due to this line:
res . result = tos2(cJSON_PrintUnformatted(js_get(root, "result")));
where cJSON_PrintUnformatted seems to return NULL because there is no 'result' key, then tos2 fails its sanity check and panics.
(generated by vlib/v/gen/json.v )

All 2 comments

I could reproduce it:
compile but fails
... with the following modification of the program:

import json

struct HassMessage {
pub:
        id           int [skip]
        message_type string [json:'type']
        event        string [raw]
        result       string [raw]
}

// Parse the message type from Home Assistant message
fn parse_hass_message(jsn string) ?HassMessage {
        hass_message := json.decode(HassMessage, jsn) or {
                return error(err)
        }
        return hass_message
}

// Test method
fn test_parse_message_type_minimal_returns_correct_type() {
        hass_msg := parse_hass_message('{"type": "testtype", "event": {"hello": "world"}}') or {
                panic(err)
        }
        eprintln('hass_msg: $hass_msg')
        assert hass_msg.message_type == 'testtype'
}

it fails due to this line:
res . result = tos2(cJSON_PrintUnformatted(js_get(root, "result")));
where cJSON_PrintUnformatted seems to return NULL because there is no 'result' key, then tos2 fails its sanity check and panics.
(generated by vlib/v/gen/json.v )

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cjmxp picture cjmxp  路  3Comments

clpo13 picture clpo13  路  3Comments

ArcDrake picture ArcDrake  路  3Comments

arg2das picture arg2das  路  3Comments

medvednikov picture medvednikov  路  3Comments