Golang 深层次 JSON 字符串转 Map 读取数据
可以使用标准库中的 json 包来解析 JSON 字符串并转换成 Map 对象。
以下是一个示例代码:
package main
import (
'encoding/json'
'fmt'
)
func main() {
jsonStr := `{\'name\': \'John\', \'age\': 30, \'address\': {\'city\': \'New York\', \'state\': \'NY\', \'zip\': \'10001\'}, \'phone\': [{\'type\': \'home\', \'number\': \'123-456-7890\'}, {\'type\': \'work\', \'number\': \'456-789-0123\'}]}`
var data map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
panic(err)
}
fmt.Println(data[\'name\'].(string))
fmt.Println(data[\'age\'].(float64))
fmt.Println(data[\'address\'].(map[string]interface{})[\'city\'].(string))
fmt.Println(data[\'phone\'].([]interface{})[0].(map[string]interface{})[\'number\'].(string))
}
解析过程中,需要定义一个 Map 变量来存储 JSON 数据,类型为 map[string]interface{},其中 key 为 string 类型,value 为 interface{} 类型,可以存储任意类型的数据。然后使用 json.Unmarshal 函数来解析 JSON 字符串,并将解析后的数据存储到 Map 变量中。
读取数据时,可以通过 Map 变量中的 key 来获取对应的 value,如果 value 是一个嵌套的 Map 对象,可以使用类型断言来将 value 转换成 map[string]interface{} 类型,并继续访问其内部的数据。如果 value 是一个数组,可以使用类型断言将 value 转换成 []interface{} 类型,并访问其中的元素。
原文地址: https://www.cveoy.top/t/topic/lZJZ 著作权归作者所有。请勿转载和采集!