簡體   English   中英

Golang如何用未引用的字段解組JSON?

[英]Golang How to Unmarshal JSON with unquoted fields?

我的[]byte切片中的 JSON 字段沒有引號。 如何自定義 Golang 的json.Unmarshal或預先格式化數據以添加必要的雙引號?

示例( Go 游樂場):

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    // Success:
    // blob := []byte(`{"license_type": "perpetual","is_trial": false}`)
    // Fails:
    blob := []byte(`{license_type: "perpetual",is_trial: false}`)

    type License struct {
        LicenseType string `json:"license_type,omitempty"`
        IsTrial bool `json:"is_trial,omitempty"`
    }
    var license License
    if err := json.Unmarshal(blob, &license); err != nil {
        fmt.Println("error:", err)
    } else {
        fmt.Printf("%+v", license)
    }
}

error: invalid character 'l' looking for beginning of object key string

此數據是 API 響應的一部分,因此任何后處理都應在不了解結構的情況下完成。

解決方案

用 yaml 解析非標准 json,它是 json 的超集。 作品。

通過上面的評論向@Peter 大喊解決方案:

您可能會成功使用 YAML 解析器,因為它是 JSON 的超集,並且引號是可選的。

工作代碼

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

func main() {
    blob := []byte(`{license_type: "perpetual",is_trial: true}`)
    type License struct {
        LicenseType string `yaml:"license_type,omitempty"`
        IsTrial bool `yaml:"is_trial,omitempty"`
    }
    var license License
    if err := yaml.Unmarshal(blob, &license); err != nil {
        fmt.Println("error:", err)
    } else {
        fmt.Printf("%+v", license)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM