[英]how to access key and value from json array in go lang
我有一個樣本如下
result = [{"Key":"9802", "Record":{"action":"Warning","status":"Created","statusid":"9802","system":"CRM","thresholdtime":"9"}}]
如何在Go lang中訪問thresholdtime值?
我正在嘗試這樣顯示: result[0]["Record"]["thresholdtime"]
error: invalid operation: result[0]["Record"] (type byte does not support indexing)
謝謝
我認為這樣的事情應該使您非常接近: https : //play.golang.org/p/ytpHTTNMjB-
使用內置的json包將您的數據解碼為結構(帶有json標簽)。 然后,就像訪問struct字段一樣簡單。
json.Unmarshal(...)示例應該可以幫助您入門。
這是一種實現方法( 前往Playground ):
func main() {
var krs []KeyRecord
err := json.Unmarshal([]byte(jsonstr), &krs)
if err != nil {
panic(err)
}
fmt.Println(krs[0].Record.ThresholdTime)
// 9
}
type KeyRecord struct {
Key int `json:"Key,string"`
Record Record `json:"Record"`
}
type Record struct {
Action string `json:"action"`
Status string `json:"status"`
StatusId int `json:"statusid,string"`
System string `json:"system"`
ThresholdTime int `json:"thresholdtime,string"`
}
var jsonstr = `
[
{
"Key": "9802",
"Record": {
"action": "Warning",
"status": "Created",
"statusid": "9802",
"system": "CRM",
"thresholdtime": "9"
}
}
]
`
您可以將JSON文檔解組為通用類型。 但是,出於多種原因不建議使用此方法,最終會導致類型信息丟失:
xs := []map[string]interface{}{}
err := json.Unmarshal([]byte(jsonstr), &xs)
if err != nil {
panic(err)
}
ttstr := xs[0]["Record"].(map[string]interface{})["thresholdtime"].(string)
fmt.Printf("%#v\n", ttstr) // Need to convert to int separately, if desired.
// "9"
使用json.Unmarshal
將數據解組為合適的數據類型。 在很多情況下,您可以(並且我會建議)為此目的使用帶有json
標記的自定義聲明的struct
類型。
但是,對於您對另一個答案的評論,可以將其編組為一個interface{}
並讓編組者確定最合適的數據類型來表示JSON結構。 例如, []interface{}
類型的切片將代表一個列表, map[string]interface{}
的映射,字典,其等效JSON的原始類型,等等。
上周,我寫了一個解析器,將這種方法用於另一個Stack問題。 這並不是要成為高性能或經過高度測試的代碼,而是要說明關鍵點:
package main
import (
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"strings"
)
// Some arbitrary JSON
const js = `
{
"key1": [
{"key2": false, "some_other_key": "abc"},
{"key3": 3}
],
"key2": {
"hello": "world"
},
"shallow": true,
"null_value": null
}`
func indentStringLines(s string, n int) string {
// Build indent whitespace - this has not been optimized!
var indent string
for i := 0; i < n; i++ {
indent += " "
}
parts := strings.Split(s, "\n")
for i := 0; i < len(parts) - 1; i++ {
parts[i] = indent + parts[i]
}
return strings.Join(parts, "\n")
}
func recursivelyPrintSlice(m []interface{}, indent int) string {
var str string
for i, val := range m {
str += fmt.Sprintf("%s: %s\n",
strconv.FormatInt(int64(i), 10),
recursivelyPrint(val, indent),
)
}
return strings.TrimSpace(str)
}
func recursivelyPrint(val interface{}, indent int) string {
var str string
switch v := val.(type) {
case bool:
str += strconv.FormatBool(v)
case float64:
str += strconv.FormatFloat(v, 'g', -1, 64)
case string:
str += v
case map[string]interface{}:
str += "{\n"
for key, childVal := range v {
str += fmt.Sprintf("%s: %s\n", key, recursivelyPrint(childVal, indent))
}
str += "}"
case []interface{}:
str += "[\n" + recursivelyPrintSlice(v, indent) + "\n]"
case nil:
str += "null"
default:
str += fmt.Sprintf(
"[unimplemented type printer for %s]",
reflect.ValueOf(v).Kind(),
)
}
return strings.TrimSpace(indentStringLines(str, indent+2))
}
func main() {
var x interface{}
err := json.Unmarshal([]byte(js), &x)
if err != nil {
log.Fatal(err)
}
fmt.Println(recursivelyPrint(x, 0))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.