S
S
Sovin2019-04-16 06:51:39
go
Sovin, 2019-04-16 06:51:39

How to handle non-existent json.RawMessage in GO?

In general, the problem:
The site may or may not return a value.
When I try to get non-existent values, the panic starts.
var settingList []*Setting
settingList[0].online
settingList[0].status...
For example, online can be passed, but status is not.
In php I do it like this:
isset($result[0]['setting']['online']) ? $result[0]['setting']['online'] : 'not specified';

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Tsvetkov, 2019-04-16
@Sovin

if len(settingList) == 0 {
    // данных нет
    return
}
for _, item := range settingList {
    if item.Online == "" {
        item.Online = "не указано"
    }
}

P
Papa, 2019-04-16
Stifflera @PapaStifflera


settingList[0].online
settingList[0].status...
If the fields of the structure are not exportable, and this piece of code says that they are, then all the fields of the structure will have empty values.
Index out of range means that settingList is empty.

U
uvelichitel, 2019-04-16
@uvelichitel

if settingList[0].online != nil {...}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question