golang读取一个未知的Json
json数据有一般常见的格式是以{}开头结尾,还有一种是以[]开头结尾。这里分别针对不同类型的json格式进行处理,具体代码如下:
1package main
2import (
3 "encoding/json"
4 "fmt"
5 "strings"
6)
7func UnknownJson(data string) {
8 if data != `` {
9 r := strings.NewReader(data)
10 dec := json.NewDecoder(r)
11 switch data[0] {
12 case 91:
13 // "[" 开头的Json
14 param := []interface{}{}
15 dec.Decode(¶m)
16 fmt.Println(param)
17 case 123:
18 // "{" 开头的Json
19 param := make(map[string]interface{})
20 dec.Decode(¶m)
21 fmt.Println(param)
22 }
23 }
24}
25func main() {
26 UnknownJson(`{"a":1}`)
27 UnknownJson(`[{"a":1},{"b":2}]`)
28}
上面代码中的91和123分别是[和{符号对应的字符码。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/golang-json/6328.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.