Похожие чаты

Gophers, how do I json.Marshal the output in my json

of a struct array with no value?
out:
{"code":"","a":null}
but I would like to do this
{"code":"","a":[{"id":"","name":""}]}

type A struct {
ID string json:"id"
Name string json:"name"
}

type B struct {
Code string json:"code"
A []A json:"a"
}

12 ответов

50 просмотров

how are you expecting a non-empty array when the slice is nil?

jeffotoni- Автор вопроса
Roman Sharkov
how are you expecting a non-empty array when the s...

all empty, I need to mount the empty struct json. I'm seeing your customize the MarshalJSON

jeffotoni- Автор вопроса

golang's stdlib encoding/json library currently marshals empty arrays as null rather than []

jeffotoni- Автор вопроса

do you know a way around? I'm not finding any other solution than to declare the structure and append something empty to make it work 😔😔

jeffotoni- Автор вопроса
Roman Sharkov
how are you expecting a non-empty array when the s...

The simplest solution I found was to make an append even empty so that Go does the allocation and thus the json of the output. b.A = append(b.A, a) {"code":"","a":[{"id":"","name":""}]}

jeffotoni- Автор вопроса
Roman Sharkov
https://go.dev/play/p/OW3MJNwjwE-

in your example I will always receive like this Foo{X: nil} so I always need to test if it's nil and if I need to tell Go that I want to print its struct .

jeffotoni
in your example I will always receive like this Fo...

can you create a playground example? I honestly don't understand the problem

jeffotoni- Автор вопроса
Edwing123
Wow that's kind of ugly

no, it doesn't. It marshals nil as null

jeffotoni- Автор вопроса
Edwing123
Wow that's kind of ugly

a lot, how would you do it?

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта