gpt4 book ai didi

json - 可以在 Go 中获取 JSON 的值

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:52 25 4
gpt4 key购买 nike

我是 Go 的新手。我正在尝试读取一个 JSON 文件并获取其中的一部分,然后使用获得的值进行操作。我的 JSON 在文件 example.json 中:

{"results":[{"statement_id":0,"series":[{"name":"cpu/node_utilization","columns":["time","distinct"],"values":[[10,1],[11,3],[13,5]]}]}]}

所以我想得到的是获取所有元素总和的“值”。在这种情况下:1+3+5

这是我的代码。我可以得到结果,但我无法得到系列。

这是我的代码:

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)

func main() {
// Open our jsonFile
jsonFile, err := os.Open("example.json")
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened example.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()

byteValue, _ := ioutil.ReadAll(jsonFile)
var all_data map[string]interface{}
json.Unmarshal([]byte(byteValue), &all_data)
fmt.Println(all_data["results"])
}

我尝试过不同的解决方案,例如 all_data["results"].(map[string]interface{})["series"])但是问题是map在数组里面,不知道怎么解决。

最佳答案

使用界面和 map

package main

import (
"encoding/json"
"fmt"
)

func main() {

byteValue := []byte(`{"results":[{"statement_id":0,"series":[{"name":"cpu/node_utilization","columns":["time","distinct"],"values":[[10,1],[11,3],[13,5]]}]}]}`)

var all_data map[string][]interface{}
json.Unmarshal([]byte(byteValue), &all_data)
fmt.Println("result:", all_data["results"])

for _, r := range all_data["results"] {
s := r.(map[string]interface{})
fmt.Println("series:", s["series"])

w := s["series"].([]interface{})
for _, x := range w {
y := x.(map[string]interface{})
fmt.Println(y)

z := y["values"].([]interface{})
fmt.Println("values:", z)
for _, v := range z {
u := v.([]interface{})
fmt.Println(u)
for _, i := range u {
val := i.(float64)
fmt.Println(val)
}
}
}
}
}

关于json - 可以在 Go 中获取 JSON 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53396957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com