This question already has an answer here:
Strange type definition syntax in Golang (name, then type, then string literal)
(1 answer)
Closed 7 years ago.
I'm learning GO and when defining structs for working with JSON like below.
type List struct {
ID string `datastore:"-"`
Name string
}
I see that there is this text in between ` sign. I have not been able to find an explanation what that signifies.
Things seem to work even without those.
They are struct tags used in Marshal'ing Go struct into JSON. In JSON, unlike Go, fields are in lowercase strings. Therefore, most use cases would be
type List struct {
ID string `json:"id"`
Name string `json:"name"`
}
In JSON
{
"id": "some id",
"name": "some name"
}
See post here
Related
This question already has answers here:
How to Unmarshal jSON with dynamic key which can't be captured as a `json` in struct: GOlang [duplicate]
(1 answer)
How to parse/deserialize dynamic JSON
(4 answers)
Closed 8 months ago.
If this has been answered somewhere else let me know but I couldn't find anything.
Basically, let's say we have the following JSON. string-id-001 can be an arbitrary string. We want to unmarshal it into a struct, and be able to access the unique id's.
{"list":{"string-id-001":{"id":"blah","name":"cool"},"string-id-002":{"id":"yas","name":"rad"}}}
Golang as far as I can tell would require something like below which doesn't work if the keyhere value is constantly changing. Eg if it's an ID
type Foo struct {
List struct {
StringID001 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-001"`
StringID002 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-002"`
} `json:"list"`
}
I've seen a similar issue in another project (which I solved with interfaces rather than structs), and I'm wondering if there's a nicer solution. Am I missing something obvious?
type payLoad struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Foo struct {
List map[string]payLoad `json:"list"`
}
This question already has answers here:
Is it possible to partially decode and update JSON? (go)
(2 answers)
How to parse a complicated JSON with Go unmarshal?
(3 answers)
golang | unmarshalling arbitrary data
(2 answers)
How to parse JSON in golang without unmarshaling twice
(3 answers)
Decoding generic JSON objects to one of many formats
(1 answer)
Closed 9 months ago.
I'm trying to represent some data in JSON where there is a list of things where each thing has some common features (ex name) and another field who's value can either be a string or an integer. For example:
{
"items": [
{
"name": "thing1",
"type": "string",
"value": "foo"
},
{
"name": "thing2",
"type": "int",
"value": 42
}
]
}
That JSON looks reasonable to me, but trying to create a data structure to deserialize (unmarshal) it into in Golang is proving difficult. I think I could do it in Java with class polymorphism, but in Go I feel trapped. I've tried many things but haven't got it. Ultimately, it comes down to lack of struct type polymorphism.
In Go, I can have a slice (list) of interfaces, but I need actual structs of different types as far as I can tell.
Any suggestions on how to represent this in Golang, and be able to unmarshal into?
Or alternatively, should I structure the JSON itself differently?
Thanks!
You can create a structure like this
type items struct {
name string
type_1 string
value interface{}
}
Interface can hold any data type, also as type is reserved keyword i have used type_1
You can do it in Go 1.18 like this:
type Data struct {
Items []struct {
Name string `json:"name"`
Type string `json:"type"`
Value any `json:"value"`
} `json:"items"`
}
func main() {
data := Data{}
// it's your json bytes
bytesData := []byte()
if err := json.Unmarshal(byteData, &data); err != nil {
log.Fatal(err)
}
}
// use data here
P.S. if you are using older versions use interface{} instead of any.
This data structure properly represents your JSON:
type Data struct {
Items []struct {
Name string `json:"name"`
Type string `json:"type"`
Value interface{} `json:"value"`
} `json:"items"`
}
Then, you can use json.Unmarshal.
If you use Go 1.18, you can use any alias of interface{}.
In addition, in Go you don't even need a type field. You can use Type assertions to determine the value type.
This question already has answers here:
Unmarshal 2 different structs in a slice
(3 answers)
Closed 4 years ago.
How would I deserialize this JSON in Go?
{
"using": [ "jmap-core", "jmap-mail" ],
"methodCalls": [
["method1", {"arg1": "arg1data", "arg2": "arg2data"}, "#1"],
["method2", {"arg1": "arg1data"}, "#2"],
["method3", {}, "#3"]
]
}
I haven't figured out how to properly get the json module to parse the methodCalls into a type. My first idea was
type MethodCall struct {
Name string
Params map[string]string
ClientId string
}
and then to use it as a list type:
type Request struct {
Using []string
MethodCalls []MethodCall
}
But this does not work. :using" is correctly parsed, but the "methocCalls" are not. Is there a way to get Go to parse this JSON into my types?
It looks like the methodCalls that you are trying to deserialize it is an array of strings instead of a struct for MethodCall.
So, Take a look at this link that I am deserializing as an array.
If you want to use the MethodCall struct you have to change the json a little bit. Take a look at this link
This question already has an answer here:
decode json including json encoded strings
(1 answer)
Closed 7 years ago.
I'm trying to Unmarshal a JSON object from an API that has a string inside of the JSON that itself is JSON, but it's escaped as a string. It looks something like this:
{
"duration": "126.61ms",
"startTime": "2016-02-19T20:01:17.884Z",
"total": 123,
"content": [
{
"dateCreated": "2016-02-19T20:01:09.181Z",
"lastUpdated": "2016-02-19T20:01:09.181Z",
"name": "name",
"stats": "{\"id\":545,\"lastUpdated\":\"2015-01-09T19:16:04.535Z\",\"all\":{\"runs\":{\"count\":123}"
}
}
I'm trying to unmarshal that into a struct like this:
type RunStatus struct {
Duration string `json:"duration"`
StartTime time.Time `json:"startTime"`
Total int `json:"total"`
Content []struct {
DateCreated time.Time `json:"dateCreated"`
LastUpdated time.Time `json:"lastUpdated"`
name string `json:"name"`
stats string `json:"stats"`
} `json:"content"`
}
What's the best way to get the escaped JSON object into a stats struct rather than it being in a string?
Do this in two phases. First unmarshal the outer object with the stats field as a string, then unmarshal that string into the stats struct. You could do a custom implementation of UnmarshalJSON so this is obfuscated but either way the only reasonable approach I know of is to do the two separately.
This question already has answers here:
Lowercase JSON key names with JSON Marshal in Go
(4 answers)
Closed 7 years ago.
i would know if json.Marshal Put Uppercase a the first letter of each name fields ? I need to encode some data with just a lowercase at each field name first letter.
just:
{
"name":"thomas"
}
instead of:
{
"Name":"thomas"
}
Thanks !
You have to add an annotation to the Name field.
Supposing your struct is:
type User struct {
Name string
}
You have to change it to:
type User struct {
Name string `json:"name"`
}
The json marshaller will replace Name with name