Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang如何使用不带引号的字段来解组JSON?_Json_Go_Unmarshalling - Fatal编程技术网

Golang如何使用不带引号的字段来解组JSON?

Golang如何使用不带引号的字段来解组JSON?,json,go,unmarshalling,Json,Go,Unmarshalling,[]字节切片中的我的JSON字段没有引号。如何自定义Golang的json.Unmarshal或预格式化数据以添加必要的双引号 示例(): 此数据是API响应的一部分,因此任何后处理都应在不了解结构的情况下进行。解决方案 使用yaml解析非标准json,yaml是json的超集。工作 通过上面的评论,大声呼喊解决方案: YAML解析器可能会成功,因为它是JSON的超集,引号是可选的 没有双qouted键的JSON根本不是JSON。对象结构表示为一对花括号,围绕零个或多个名称/值对(或成员)。名

[]字节
切片中的我的JSON字段没有引号。如何自定义Golang的
json.Unmarshal
或预格式化数据以添加必要的双引号

示例():


此数据是API响应的一部分,因此任何后处理都应在不了解结构的情况下进行。

解决方案

使用yaml解析非标准json,yaml是json的超集。工作

通过上面的评论,大声呼喊解决方案:


YAML解析器可能会成功,因为它是JSON的超集,引号是可选的


没有双qouted键的JSON根本不是JSON。
对象结构表示为一对花括号,围绕零个或多个名称/值对(或成员)。名称是一个字符串
,您可以查看仍然可以解析它的包。其中一个是,但它似乎考虑了结构标记。我不久前写过一篇文章,将JavaScript表示法对象转换为JSON,然后可以使用stdlib
编码/JSON
对其进行解码,也许这是您可以使用的东西YAML解析器可能会成功,因为它是JSON的超集,引号是可选的。
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
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)
    }
}