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 5 months ago.
Improve this question
https://go.dev/play/p/L2IJp-ehA2S
The following program provides me the required output (ccc09e). But this is correct approach or this can be improved.
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string
}
func main() {
empJson := `[{"name":"ccc09e"}]`
var emp []People
json.Unmarshal([]byte(empJson), &emp)
s := fmt.Sprintf("%v", emp[0])
s = s[1 : len(s)-1]
fmt.Println(s)
}
I got the required output https://go.dev/play/p/L2IJp-ehA2S and I need improvement to the program.
Looks like you want the Name of the First element of People array in s
No need to do string manipulations. Just access it directly
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string
}
func main() {
empJson := `[{"name":"ccc09e"}]`
var emp []People
json.Unmarshal([]byte(empJson), &emp)
s := emp[0].Name
fmt.Println(s)
}
https://go.dev/play/p/O2hiGuSyM53
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 2 years ago.
Improve this question
I don't understand why this doesn't work for this type of structure.
package main
import (
"fmt"
)
var myStruct struct {
number float64
word string
toggle bool
}
myStruct.number = 3.14
myStruct.word = "pie"
myStruct.toggle = true
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
If I try to change myStruct.number outside main, I get a compilation error syntax error: non-declaration statement outside function body, but it works fine inside the function. With variables or other types of data structures, it works fine to change values outside main scope, but not with struct.
The program is an example from Head first Go, and even if I searched at least three more books and google for more information, I haven't found something similar that would be better explained.
https://play.golang.org/p/brocZzWuRae
package main
import (
"fmt"
)
var myStruct = struct {
number float64
word string
toggle bool
}{
number: 3.14,
word: "pie",
toggle: true,
}
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
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 currently trying to serialize some string slice in a CSV without saving output to a file. I saw some examples using bytes.Buffer but even my the smallest test doesn't work. I don't know how to debug this, the code compiles without warning and doesn't throw error after writer.Flush(). It also works correctly with saving result to a file or piping it directly to standard output
Any help would be appreciated :)
Thx.
PS: the final print is just a test. I know i can use csv.NewWriter(os.stdout) to do so (and it works) but it doesn't fit my needs. I really would like to get the result in a byte array.
package main
import (
"bytes"
"encoding/csv"
"fmt"
)
func main() {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
writer.Write([]string{"1", "2", "3", "4"})
writer.Write([]string{"5", "6", "7", "8"})
defer writer.Flush()
if err := writer.Error(); err != nil {
panic(err)
}
fmt.Println(buffer.Bytes())
}
You are deferring the Flush call, making it execute after the fmt.Println call. Call Flush immediately:
package main
import (
"bytes"
"encoding/csv"
"fmt"
)
func main() {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
writer.Write([]string{"1", "2", "3", "4"})
writer.Write([]string{"5", "6", "7", "8"})
writer.Flush()
if err := writer.Error(); err != nil {
panic(err)
}
fmt.Println(buffer.String())
}
https://play.golang.org/p/BHTyfsuf0tY
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm a bit new to golang coming from a nodejs background. I'm a bit confused as to why certain functions have a function signature in the following format
function readContents(var1 type, var2 *type)
If we consider the above function, readContents, reads contents into a pointer of var2. Is this a standard practice in the go language where you pass parameters in and expect them to have return values. A practical example is here https://github.com/vmihailenco/msgpack. If you look at the quickstart it has the following code
err = msgpack.Unmarshal(b, &item)
I would normally expect it to return the value rather than modify the incoming value in &item.
Return values are generally preferred.
The caller must specify the type of the target value to msgpack.Unmarshal. The Unmarshal function can be restructured to use a return value like this:
func Unmarshal(p []data, exampleValueOfType interface{}) (interface{}, error)
The calling code will look something like this:
v, err := msgpack.Unmarshal(b, (*X)(nil))
if err != nil {
// handle error
}
x := v.(*X)
It's simpler for the caller to pass to pass a target value. This avoids the type assertion and mentioning the type twice in the code:
var x X
if err := msgpack.Unmarshal(b, &x) {
// handle error
}
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 4 years ago.
Improve this question
I work with Go.
I would like to parse a JSON file. But I only need just one array from the JSON file, not all the structure.
This is the JSON file : link
I only need the array of items.
How can I extract just this array from the JSON?
That depends of the definition of your structs. if you want only the array of items, you should unmarshal the main structure and then get the items array.
something like this
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type Structure struct {
Items []Item `json:"items"`
}
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
data, err := ioutil.ReadFile("myjson.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
structure := new(Structure)
json.Unmarshal(data, structure)
theArray := structure.Items
fmt.Println(theArray)
}
The Unmarshal will ignore the fields you don't have defined in your struct. so that means you should add only what you whant to unmarshal
I used this JSON
{
"total_count": 123123,
"items": [
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
]
}
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 5 years ago.
Improve this question
I have a very simple http resonse in my server where i json encode a struct. But its sending a blank of just {}
I don't know if i am doing it wrong but i get no errors. This is my json encode:
// Set uuid as string to user struct
user := User{uuid: uuid.String()}
fmt.Println(user) // check it has the uuid
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusCreated)
json.NewEncoder(responseWriter).Encode(user)
On the recieving end the data has:
Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}
Why does it not give me the uuid data? Am i doing something wrong with my encoding?
Export the field name by making the first character of the identifier's name a Unicode upper case letter (Unicode class "Lu").
Try this:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type User struct {
Uuid string
}
func handler(responseWriter http.ResponseWriter, r *http.Request) {
user := User{Uuid: "id1234657..."} // Set uuid as string to user struct
fmt.Println(user) // check it has the uuid
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusCreated)
json.NewEncoder(responseWriter).Encode(user)
}
func main() {
http.HandleFunc("/", handler) // set router
err := http.ListenAndServe(":9090", nil) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
output(http://localhost:9090/):
{"Uuid":"id1234657..."}