解碼未知結構的JSON資料

2021-07-08 15:46:54 字數 1343 閱讀 5729

如果要解碼一段未知結構的json,只需將這段json資料解碼輸出到乙個空介面即可。在解碼json資料的過程中,json資料裡邊的元素型別將做如下轉換:

1)json中的布林值將會轉換為go中的bool型別;

2)數值會被轉換為go中的float64型別;

3)字串轉換後還是string型別;

4)json陣列會轉換為inte***ce{}型別;

5)json物件會轉換為map[string]inte***ce{}型別;

6)null值會轉換為nil。

在go的標準庫encoding/json包中,允許使用map[string]inte***ce{}和inte***ce{}型別的值來分別存放未知結構的json物件或陣列,示例**如下:

package main

import (

"fmt"

"encoding/json"

)func main() `)

var r inte***ce{}

err := json.unmarshal(b, &r)

if err == nil

gobook, ok := r.(map[string]inte***ce{})

if ok :

fmt.println(k, "is an array:")

for i, iv := range v2

default:

fmt.println(k, "is another type not handle yet")

}} }

}

輸出結果

map[publisher:ituring.com.cn ispublished:true price:9.99 sales:1e+06 title:go語言程式設計 authors:[xushiwei hughlv pandaman guaguasong hantuo bertyuan xudaoli]]

ispublished is bool true

price is another type not handle yet

sales is another type not handle yet

title is string go語言程式設計

authors is an array:

0 xushiwei

1 hughlv

2 pandaman

3 guaguasong

4 hantuo

5 bertyuan

6 xudaoli

publisher is string ituring.com.cn

編譯碼JSON資料

package main import fmt encoding json log type book struct func main ituring.com.cn true,9.99,b,json.marshal gobook log.printf b v n b comparedbytearr...

GO語言 處理未知JSON資料

當未知json資料時 package main import encoding json fmt io ioutil log func readfilefrompath path string byte return content func main json.unmarshal content,...

JSON資料編碼 解碼框架

編碼 把資料寫成json結構過程 解碼 把資料從json文件中讀取的過程,就是將字串分析之後讀入到乙個集合物件中,這個集合物件的結構可能是陣列,也可能是字典。編碼 解碼框架 1 sbjson,比較老得json編碼 解碼框架,現在更新任然很頻繁,支援arc 2 touchjson,比較老得json編碼...