golang如何解析json格式

  介绍

小编给大家分享一下golang如何解析json格式,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

项目中客户端和服务端的交互数据部分为json,因此在服务端就得解析,复杂的json解析起来其实还是挺费劲的。
交互的数据类似如下格式:

{“sn": 1、“ls":假的,“bg": 0,“ed": 0,“ws": [{“bg": 0,“cw": [{“sc": 0,“w":“还“}]},{“bg": 0,“cw": [{“sc": 0,“w":“有点“}]},{“bg": 0,“cw": [{“sc": 0,“w":“眼熟“}]}]}

需要将json格式中的w字段取出来,并且拼成结果串进行展示

<李>

从json数组中获取ws

<李>

ws是数组,数组元素为对象

<李>

cw是数组,数组元素为对象

<李>

w是字符串

<李>

从连续波遍历获取w字段

初步实现如下:

func  RecResultJsonToPlain (), {,,, var  recResult  string ,,, var  dat  map [string]接口{}   ,,,json.Unmarshal([]字节(json_str),,, dat),,,, if  v, ok :=, dat [“ws"];, ok  {   ,,,,,,,ws :=,诉([]接口{}),,,,,,,,for 我,wsItem :=, range  ws  {   ,,,,,,,,,,,wsMap :=, wsItem。(map [string]接口{}),,,,,,,,,,,,if  vCw, ok :=, wsMap [“cw"];, ok  {   ,,,,,,,,,,,,,,,cw :=, vCw。([]接口{}),,,,,,,,,,,,,,,,for 我,cwItem :=, range  cw  {   ,,,,,,,,,,,,,,,,,,,cwItemMap :=, cwItem。(map [string]接口{}),,,,,,,,,,,,,,,,,,,,if  w, ok :=, cwItemMap [“w"];, ok  {   ,,,,,,,,,,,,,,,,,,,,,,,recResult =, recResult  + w。(字符串)   ,,,,,,,,,,,,,,,,,,,}   ,,,,,,,,,,,,,,,}   ,,,,,,,,,,,}   ,,,,,,,}   ,,,}   ,,,fmt.Println (recResult)   }

这样实现,一层一层去转换类型,再去获取元素有点麻烦。既然是已知的json数据结构,那么可以定义好结构体,再去进行解析。

type  CWItem  struct  {   ,,,SC  int32 ,“json:“sc"”   ,,,W , string “json:“w"”} type  WSItem  struct  {   ,,,CW  [] CWItem} type  IatResult  struct  {   ,,,SN  int32 ,,,“json:“sn"”   ,,,LS  bool ,,,,的json:“ls"   ,,,BG  int32 ,,,“json:“bg"”   ,,,ED  int32 ,,,“json:“ed"”   ,,,WS  [] WSItem “json:“ws"”}

<强>注意定义的时候变量名第一个字母要大写,也可以使用工具来自动生成定义https://mholt.github。io/json-to-go;用工具生成的挺漂亮:

type  AutoGenerated  struct  {   ,,,Sn  int “json:“sn"”   ,,,Ls  bool “json:“ls"”   ,,,Bg  int “json:“bg"”   ,,,Ed  int “json:“ed"”   ,,,Ws  [] struct  {   ,,,,,,,Bg  int “json:“bg"”   ,,,,,,,Cw  [] struct  {   ,,,,,,,,,,,Sc  int “json:“sc"”   ,,,,,,,,,,,W  string “json:“w"”   ,,,,,,,},的json:“cw"   ,,,},的json:“ws"   }
 func  RecResultJsonToPlain (jsonResult []字节)(recPlainResult 字符串),,{,,,var  r  IatResult
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null

golang如何解析json格式