Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support json array? #119

Closed
mailbaoer opened this issue Mar 15, 2016 · 2 comments
Closed

support json array? #119

mailbaoer opened this issue Mar 15, 2016 · 2 comments

Comments

@mailbaoer
Copy link

I have a json array column named 'content', example value like:
[{"time": 1458033154, "user": "baoer", "detail": "hello"}, {"time": 1458033155, "user": "beiguo", "detail": "hi"}]
when I find a record from my table ,It raised that "invalid character ',' after object key", how can I change it, my struct defined the content column is Content []interface{}

@mailbaoer mailbaoer changed the title support support json array? Mar 15, 2016
@vmihailenco
Copy link
Member

Works just fine for me. Do you use pg.v4?

package main

import (
    "fmt"

    "gopkg.in/pg.v4"
)

type Test struct {
    Slice []interface{}
}

func main() {
    db := pg.Connect(&pg.Options{
        User: "postgres",
    })

    _, err := db.Exec(`create table if not exists tests (slice jsonb)`)
    if err != nil {
        panic(err)
    }

    err = db.Create(&Test{
        Slice: []interface{}{map[string]interface{}{"hello": "world"}},
    })
    if err != nil {
        panic(err)
    }

    var tests []Test
    err = db.Model(&tests).Select()
    if err != nil {
        panic(err)
    }
    fmt.Println(tests)
}

@mailbaoer
Copy link
Author

I found the problem,my column type is top level json arrays, so need more work for decode

package main

import "fmt"
import "encoding/json"

type Server struct {
    ServerName string
    ServerIP   string
}

func main() {
    s := make([]Server, 1)
    str := `[{"serverName":"server1","serverIP":"127.0.0.1"},{"serverName":"server2","serverIP":"127.0.0.2"}]`
    json.Unmarshal([]byte(str), &s)
    fmt.Println(s)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants