Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
coders. I'm completely newbie to Go and got a little bit confused about json.Unmarshal output:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []struct{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
Output:
[{} {} {}]
Why is it empty?
You can try it here: https://play.golang.org/p/yztOLJADIXx
If you want to unmarshal JSON objects without knowing their fields, use a map[string]interface{}:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []map[string]interface{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
Try it here: https://play.golang.org/p/iPlBgguE8Kk
However, if you know the names of the fields you're going to unmarshal, you should define the structure. In your case it would look like that:
type Person struct {
First string `json:"First"`
Last string `json:"Last"`
Age int `json:"Age"`
Sayings []string `json:"Sayings"`
}
Try this solution here: https://play.golang.org/p/jCrCteYTaIf
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am unable to parse json that has string keys and array as value ending up with json: Unmarshal(non-pointer map[string]interface {}) error.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var s map[string]interface{}
err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), s)
if err != nil {
panic(err)
}
fmt.Println("Nice parse!")
}
https://go.dev/play/p/AXlF8I-f9-p
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. Add &s as a parameter
err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), &s)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my GoLang program which invokes a REST API, i need to collect the responses from different REST API's which return slices of pointers of the same struct.
I am attempting to concatenate the slices of pointers using append and i am getting error similar to what is shown below.
I think append does not support such an operation , is there any alternative to this ?
cannot use response (type []*string) as type *string in append
A go playground link for the problem ,i am trying to demonstrate is given here.
https://play.golang.org/p/lnzSd2kbht0
package main
import (
"fmt"
)
func main() {
var fruits []*string
response := GetStrings("Apple")
fruits = append(fruits, response...)
response = GetStrings("Banana")
fruits = append(fruits, response...)
response = GetStrings("Orange")
fruits = append(fruits, response...)
if fruits == nil || len(fruits) == 0 {
fmt.Printf("Nil Slice")
} else {
fmt.Printf("Non nil")
fmt.Printf("%v", fruits)
}
}
func GetStrings(input string) []*string {
var myslice []*string
myslice = append(myslice, &input)
return myslice
}
I cannot change the REST API or the function signature to return the slice of structs itself.
To append all elements of a slice to another slice, use:
resultSlice=append(slice1, slice2...)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to test a URL via a Go function. In our environment, we have our hostnames set up per environment, like https://www/examplesite20193.domain.org Here is a simple example of what I've got:
package main
import (
"fmt"
"net/http"
"log"
)
func main() {
versionMaj := "2019"
versionMin := "3"
endpoint := versionMaj+versionMin
resp, err:= http.Get("https://www.examplesite%s.domain.org", endpoint)
if err != nil {
log.Fatal(err)
}
fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))
}
When I test this, it's stating too many arguments in call to http.Get have (string, string) want (string).
Is there a way to pass in a parameter, like the endpoint one I have specified?
Probably you're looking to something like this:
resp, err:= http.Get(fmt.Sprintf("https://www.examplesite%s.domain.org", endpoint))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to parse a json-like string which looks like this.
"abc:9, bar:3"
What I would like to have at the end is a map[string]int which looks like this:
map[string]int{"abc":9, "bar":3}
I have gotten as far as splitting it into a set of 'pairs', like so:
`["abc:9", "bar:3"]
I am struggling with how to get that structure into the final map[string]int. I have tried ranging over the slice, but I am missing how to actually get it into the map.
val := "abc:9, bar:3"
lsd := make(map[string]int)
c := strings.Split(val, ",")
for k, v := range c {
lsd = v[k] // where I am struggling, I know this is wrong, but I can't seem to find the proper syntax and tools for this
}
Can anyone point me in the right direction to end up with the map[string]int I am looking for here?
This is a tiny bit cheesy but I was having trouble making fmt.Sscanf grok the pattern, so I am just splitting again. And you may have been missing strconv - strconv.Atoi is a quick converter.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
lsd := make(map[string]int)
toParse := "abc:5, foo:5"
parts := strings.Split(toParse, ", ")
for _, p := range parts {
results := strings.SplitN(p, ":", 2)
val, err := strconv.Atoi(results[1])
if err != nil {
panic(err) //probably want to do somethig better
}
lsd[results[0]] = val
}
fmt.Printf("%#v", lsd)
}
map[string]int{"abc":5, "foo":5}
https://play.golang.org/p/UadibEzTXWU
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to unmarshal json data. The slice inside is deliberately without quotes, because this is what I am getting from https (added manually \ before ")
data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"
into Message struct:
type Message struct {
QueryEndTime string `json:"queryEndTime"`
Message []string `json:"message"`
}
but I am getting correct QueryEndTime and empty Message. I tried to change Message type but it always stays empty
var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s\nMessage: %s\n", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []
See it in go playground https://play.golang.org/p/on0_cSKb0c.
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
QueryEndTime string `json:"queryEndTime"`
// you need to use a struct can use anon struct
Message []struct {
SpamScore int `json:"spamScore"`
PhishScore int `json:"phishScore"`
} `json:"message"`
}
func main() {
var message Message
// You can use backticks to for your example JSON, so that you don't have to escape anything.
data := `{
"queryEndTime" : "2017-11-15T14:39:00Z",
"message" : [
{"spamScore":67, "phishScore":0}
]
}`
// please check for errors
err := json.Unmarshal([]byte(data), &message)
if err != nil {
fmt.Println(err)
}
// +v prints structs very nicely
fmt.Printf("%+v\n", message)
}
https://play.golang.org/p/Mu3WZCej3L
Have fun!