beego之json重新打包

本文介绍了如何在Beego框架中处理JSON数组,通过append方法动态添加元素到JSON数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近的一个需求是,去读取数据库的数据,但是里面有一个字段本来应该是json来存的,但是由于存储方便,直接把它变成字符,在后台提取处理的时候才吧它变回json。我在这里是用json存储提取到的struct里存储。但是后面需要在这个json添加json数组。由于对golang中的struct操作不熟悉,这里搞了我2天。其实里面就是涉及到slice的操作。因为在结构体中,定义jsong数组是
type Gwlog struct {
    Acname            string
    Ip                string
    Auth_clients      string
    Ap_num            string
    Online_ap         string
    Offline_ap        string
    Timestarp         string
    Gwid              string
    Arp_num           string
    Offline_ap_status string
    Aplist            []Offlineapmsg

}

其中Aplist就是json数组,它的定义就是slice,所以如果需要添加json数组,直接用append就可以了,具体beego代码如下:

package controllers

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Gwlog struct {
	A            string
	B            []Offlineapmsg
}

type Offlineapmsg struct {
	Mac    string
	Ip     string
	Apname string
}

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)

	orm.RegisterDataBase("rou", "mysql", "root:newpasswd@tcp(localhosg:33306)/yk_log?charset=utf8")
}

type RouController struct {
	beego.Controller
}

func (c *RouController) Get() {
	o := orm.NewOrm()
	o.Using("rou")
	var gwmsgs []Gwlog
	var j int64
	num, err := o.Raw("select *from ac_status").QueryRows(&gwmsgs)
	if err != nil {
		fmt.Println("user nums: ", err)
	}
	for j = 0; j < num; j++ {

		offline_ap_msg_every := strings.Split(gwmsgs[j].Offline_ap_status, ";")

		for i := 0; i < len(offline_ap_msg_every); i++ {
			offline_ap_msg_each := strings.Split(offline_ap_msg_every[i], ",")
			if len(offline_ap_msg_each) == 1 {
				fmt.Println("continue")
				continue
			}

			gwmsgs[j].Aplist = append(gwmsgs[j].Aplist, Offlineapmsg{Mac: offline_ap_msg_each[1], Ip: offline_ap_msg_each[2], Apname: offline_ap_msg_each[0]})
		}
	}

	c.Data["json"] = gwmsgs
	c.ServeJSON()
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值