【问题标题】:How can we read a json file as json object in golang我们如何在golang中将json文件读取为json对象
【发布时间】:2017-04-29 09:00:06
【问题描述】:

我在本地机器上存储了一个 JSON 文件。我需要在一个变量中读取它并循环遍历它以获取 JSON 对象值。如果我在使用 ioutil.Readfile 方法读取文件后使用 Marshal 命令,它会给出一些数字作为输出。这是我几次失败的尝试,

尝试1:

plan, _ := ioutil.ReadFile(filename) // filename is the JSON file to read
var data interface{}
err := json.Unmarshal(plan, data)
if err != nil {
        log.Error("Cannot unmarshal the json ", err)
      }
fmt.Println(data)

它给了我以下错误,

time="2016-12-13T22:13:05-08:00" level=error msg="Cannot unmarshal the json json: Unmarshal(nil)"
<nil>

尝试 2:我尝试将 JSON 值存储在结构中,然后使用 MarshalIndent

generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct
fmt.Println(string(generatePlan))

它以字符串形式给我输出。但是如果我将输出转换为字符串,那么我将无法将其作为 JSON 对象循环。

我们如何在 golang 中将 JSON 文件读取为 JSON 对象?有可能这样做吗? 任何帮助表示赞赏。提前致谢!

【问题讨论】:

    标签: json go file-read


    【解决方案1】:

    json.Unmarshal 填充的值需要是一个指针。

    来自GoDoc

    Unmarshal 解析 JSON 编码的数据并将结果存储在 v 指向的值中。

    所以你需要做以下事情:

    plan, _ := ioutil.ReadFile(filename)
    var data interface{}
    err := json.Unmarshal(plan, &data)
    

    您的错误(Unmarshal(nil)) 表示读取文件有问题,请查看ioutil.ReadFile返回的错误


    另外请注意,在 unmarshal 中使用空接口时,您需要使用 type assertion 将底层值作为原始类型获取。

    为了将 JSON 解组为接口值,Unmarshal 存储以下之一 这些在接口值:

    bool, for JSON booleans
    float64, for JSON numbers
    string, for JSON strings
    []interface{}, for JSON arrays
    map[string]interface{}, for JSON objects
    nil for JSON null
    

    使用Unmarshal 来使用具体结构来填充您的 json 始终是一种更好的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-21
      • 2015-06-10
      • 2019-11-25
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      相关资源
      最近更新 更多