go语言json嵌套数组Map用法

                          go语言json嵌套数组Map用法

一、转换思路

  •     一个json对象就是一个map
  •     一个json数组就是一个切片
  •     json数组放对象就是相当于切片里面放map

二、实例

package main

import(
	"encoding/json"
	"fmt"
)

func main(){
	var Order = make(map[string]interface{})

	Order["order_id"] = "20190707212318"

	Order["order_price"] = 21.3


	Goods := make([]map[string]interface{},2)

	Goods[0] = make(map[string]interface{})
	Goods[0]["goods_name"] = "手机"
	Goods[0]["goods_price"] = 23.1

	Goods[1] = make(map[string]interface{})
	Goods[1]["goods_name"] = "电脑"
	Goods[1]["goods_price"] = 123.1


	GoodsColor := make([]map[string]interface{},2)

	GoodsColor[0] = make(map[string]interface{})
	GoodsColor[0]["good_color"] = "红色"

	GoodsColor[1] = make(map[string]interface{})
	GoodsColor[1]["good_color"] = "蓝色"

	Goods[0]["goods_color"] = GoodsColor
	Goods[1]["goods_color"] = GoodsColor


	Order["good"] = Goods 

	data ,_:= json.Marshal(Order)

	fmt.Println(string(data))

	/*
{
	"good": [{
		"goods_color": [{
			"good_color": "红色"
		}, {
			"good_color": "蓝色"
		}],
		"goods_name": "手机",
		"goods_price": 23.1
	}, {
		"goods_color": [{
			"good_color": "红色"
		}, {
			"good_color": "蓝色"
		}],
		"goods_name": "电脑",
		"goods_price": 123.1
	}],
	"order_id": "20190707212318",
	"order_price": 21.3
}
	*/


	var temp = make(map[string]interface{})

	err := json.Unmarshal(data,&temp)

	if err !=nil{
		fmt.Println(err)
	}

	fmt.Println(temp)


	//map[good:[map[goods_color:[map[good_color:红色] map[good_color:蓝色]] goods_name:手机 goods_price:23.1] map[goods_color:[map[good_color:红色] map[good_color:蓝色]] goods_name:电脑 goods_price:123.1]] order_id:20190707212318 order_price:21.3]



}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值