#Create new JSON from existing struct

18 messages · Page 1 of 1 (latest)

tranquil cypress
#

I'm not sure if that is a dumb question to ask, but I couldn't really find anything that is similar, more just how to make JSON structs.
I have an existing struct that is filled with data in the following format:
[{CA 1} {DE 2} {FR 1} {GB 3} {NZ 2} {RU 2} {US 1}]
I am looking to create a JSON string in the format like this:
{"CA":1,"DE":2,"FR":1,"GB":3,"NZ":2,"RU":2, "US":1}
What would be a good way to go about doing this? I can imagine looping through the struct and assigning something the values of it, but not really sure where to go

#

the code to create the first piece of data is this:

func test(ctx iris.Context) {
    db, err := sqlx.Connect("mysql", "root:@(localhost:3306)/db")
    if err != nil {
        log.Fatalln(err)
    }
    table := []GEO{}
    rows1, err := db.Queryx("SELECT geo,COUNT(*) as cnt FROM map GROUP BY geo;")
    if err != nil {
        log.Fatal(err)
    }
    for rows1.Next() {
        var tables GEO
        err := rows1.StructScan(&tables)
        if err != nil {
            log.Fatal(err)
        }

        table = append(table, tables)
        fmt.Println(table)
    }

    ctx.ViewData("jsondata", table)
    if err := ctx.View("test.html"); err != nil {
        ctx.HTML("<h3>%s</h3>", err.Error())
        return
    }
}```
#

if you can actually have the code within the function test to make the json, that would be more optimal, but looking t structs and stuff isn't a strong suit for me

uneven gazelle
#

have you tried just using json.Marshal

tranquil cypress
#
type GEO struct {
    Geo string `json:"geo"`
    Cnt int `json:"cnt"`
}``` struct is made like this
tranquil cypress
#

but I am assuming that is because it is not the right way to go about doing that

#

I tried like this go j, err := json.Marshal(tables) if err != nil { log.Fatalf("Error occured during marshaling. Error: %s", err.Error()) } table = append(table, string(j))

#

I can do this client side, but I have worries about performance, since I will use the same code on html tables that will store ALOT of info

#

or a lot of rows rather

uneven gazelle
#

what is the error?

tranquil cypress
tranquil cypress
#

resolved

#

dw

#

im writing the code rn that helped

lost charm
#

table is a list of GEO, not strings

tranquil cypress
#
func (b GEO) MakeJson(tables []GEO) string {
    m := make(map[string]int)

    for i := range tables {
        m[tables[i].Geo] += tables[i].Cnt
    }
    mapJson, err := json.Marshal(m)
    if err != nil {
        return ""
    }

    return string(mapJson)
}```
calling function:
```go
fmt.Println(tables.MakeJson(table))```
output : ```{"CA":1,"DE":2,"FR":1,"GB":3,"NZ":2,"RU":2,"US":1}
tranquil cypress