在mgo中出现错误:结果没有字段或方法。

huangapple go评论73阅读模式
英文:

error in mgo: result has no field or method

问题

我有以下代码

package main

import (
    "encoding/json"
    "fmt"
    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
)

func insertEntry(j *map[string]interface{}, entry string) {
    err := json.Unmarshal([]byte(entry), j)
    if err != nil {
        panic(err)
    }

}

func main() {
    c1 := `{
    "mw" : 42.0922,
        "ΔfH°gas" : {
          "value" : 372.38,
          "units" : "kJ/mol"
        },
        "S°gas" : {
          "value" : 216.81,
          "units" : "J/mol×K"
        },
        "index" : [
          {"name" : "mw", "value" : 42.0922},
          {"name" : "ΔfH°gas", "value" : 372.38},
          {"name" : "S°gas", "value" : 216.81}
        ]
        }`

    c2 := `{
    "name": "silicon",
    "mw": 32.1173,
    "index": [
    {
        "name": "mw",
        "value": 32.1173
    }
    ]
    }`

    var m map[string]interface{}

    insertEntry(&m, c1)
    insertEntry(&m, c2)
    chemical := m["ΔfH°gas"].(map[string]interface{})
    fmt.Println("value: ", chemical["value"].(float64))
    fmt.Println("units: ", chemical["units"].(string))

    session, err := mgo.Dial("localhost")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("chemicals")
    err = c.Insert(&m)
    if err != nil {
        panic(err)
    }

    result := &m
    err = c.Find(bson.M{"name": "silicon"}).One(&result)
    if err != nil {
        panic(err)
    }

    fmt.Println(result)
    fmt.Println("mw:", (*result)["mw"])
}

并得到以下错误

$ go run chemeo.go
# command-line-arguments
./chemeo.go:78: result.mw undefined (type *map[string]interface {} has no field or method mw)

我如何打印出mw?

提前谢谢。

英文:

I have the following code

package main

import (
    "encoding/json"
    "fmt"
    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
)

func insertEntry(j *map[string]interface{}, entry string) {
    err := json.Unmarshal([]byte(entry), j)
    if err != nil {
	    panic(err)
    }

}

func main() {
    c1 := `{
    "mw" : 42.0922,
	    "ΔfH°gas" : {
	      "value" : 372.38,
	      "units" : "kJ/mol"
	    },
	    "S°gas" : {
	      "value" : 216.81,
	      "units" : "J/mol×K"
	    },
	    "index" : [
	      {"name" : "mw", "value" : 42.0922},
	      {"name" : "ΔfH°gas", "value" : 372.38},
	      {"name" : "S°gas", "value" : 216.81}
	    ]
	    }`

    c2 := `{
    "name": "silicon",
    "mw": 32.1173,
    "index": [
	{
	    "name": "mw",
	    "value": 32.1173
	}
	]
    }`

    var m map[string]interface{}

    insertEntry(&m, c1)
    insertEntry(&m, c2)
    chemical := m["ΔfH°gas"].(map[string]interface{})
    fmt.Println("value: ", chemical["value"].(float64))
    fmt.Println("units: ", chemical["units"].(string))

    session, err := mgo.Dial("localhost")

    if err != nil {
	    panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("chemicals")
    err = c.Insert(&m)
    if err != nil {
	    panic(err)
    }

    result := &m
    err = c.Find(bson.M{"name": "silicon"}).One(&result)
    if err != nil {
	    panic(err)
    }

    fmt.Println(result)
    fmt.Println("mw:", result.mw)
}

and got the following error

$ go run chemeo.go
# command-line-arguments
./chemeo.go:78: result.mw undefined (type *map[string]interface {} has no field or method mw)

How could I print mw out?

Thank you in advance.

答案1

得分: 2

result 是一个 map[string],所以你可以通过 result["mw"] 来访问值。这个 map 条目的值将是 interface{} 类型,Go 的最通用类型,所以你需要将其转换为 float 类型才能使用。参见 类型转换

我从未使用过 mgo,但它似乎在底层使用了 encoding/json。如果是这样的话,你可以定义一个与你的 JSON 结构匹配的结构体,然后 encoding/json 将能够将 mgo 的响应解组成它。

英文:

result is a map[string], so you can access the value with result["mw"]. The value of this map entry will be of type interface{}, Go's most general type, so you will have to convert it to a float to use it. See type conversions.

I never used mgo, but it seems it uses encoding/json under the hood. If so, you can define a struct that matches the structure of your JSON and encoding/json will be able to unmarshal mgo's response into it.

答案2

得分: 0

很不幸,我从未使用过mgo,但是根据错误信息,我可能会尝试:

fmt.Println("mw:", result["mw"])
英文:

Unfortunately I never used mgo, but looking at the error message, I would probably try

fmt.Println("mw:", result["mw"])

huangapple
  • 本文由 发表于 2013年3月14日 21:27:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/15410606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定