golang中的严格json解析器

Kir*_*Kir 15 json go

在Go中,我有一些来自第三方API的JSON,然后我正在尝试解析它:

b := []byte(`{"age":21,"married":true}`)
var response_hash map[string]string
_ = json.Unmarshal(b, &response_hash)
Run Code Online (Sandbox Code Playgroud)

但它失败(response_hash变空)并且Unmarshal只能处理带引号的JSON:

b := []byte(`{"age":"21","married":"true"}`)
var response_hash map[string]string
_ = json.Unmarshal(b, &response_hash)
Run Code Online (Sandbox Code Playgroud)

有没有办法从第三方API读取第一个版本的JSON?

Dan*_*iel 23

Go是一种强类型语言.您需要指定JSON编码器所期望的类型.您正在创建字符串值的映射,但您的两个json值是整数和布尔值.

这是一个带结构的工作示例.

http://play.golang.org/p/oI1JD1UUhu

package main

import (
    "fmt"
    "encoding/json"
    )

type user struct {
    Age int
    Married bool
}

func main() {
    src_json := []byte(`{"age":21,"married":true}`)
    u := user{}
    err := json.Unmarshal(src_json, &u)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Age: %d\n", u.Age)
    fmt.Printf("Married: %v\n", u.Married)
}
Run Code Online (Sandbox Code Playgroud)

如果您想以更动态的方式执行此操作,可以使用interface {}值的映射.您只需在使用值时键入断言.

http://play.golang.org/p/zmT3sPimZC

package main

import (
    "fmt"
    "encoding/json"
    )

func main() {
    src_json := []byte(`{"age":21,"married":true}`)
    // Map of interfaces can receive any value types
    u := map[string]interface{}{}
    err := json.Unmarshal(src_json, &u)
    if err != nil {
        panic(err)
    }
    // Type assert values
    // Unmarshal stores "age" as a float even though it's an int.
    fmt.Printf("Age: %1.0f\n", u["age"].(float64))
    fmt.Printf("Married: %v\n", u["married"].(bool))
}
Run Code Online (Sandbox Code Playgroud)

  • 另外,不要忘记,如果你想为结构使用不同的变量名,你可以使用`\`json:"valuename"\``http://play.golang.org/p/8QD2yfb与json变量接口-fy (5认同)
  • 我只想补充一点,这篇博文详细介绍了使用第二种方法:http://blog.golang.org/2011/01/json-and-go.html (4认同)