golang的json操作
package main import (
"encoding/json"
"fmt"
"os"
) type ConfigStruct struct {
Host string `json:"host"`
Port int `json:"port"`
AnalyticsFile string `json:"analytics_file"`
StaticFileVersion int `json:"static_file_version"`
StaticDir string `json:"static_dir"`
TemplatesDir string `json:"templates_dir"`
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
} type Other struct {
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
} func main() {
jsonStr := `{"host": "http://localhost:9090","port": 9090,"analytics_file": "","static_file_version": 1,"static_dir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}` //json str 转map
var dat map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {
fmt.Println("==============json str 转map=======================")
fmt.Println(dat)
fmt.Println(dat["host"])
} //json str 转struct
var config ConfigStruct
if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(config)
fmt.Println(config.Host)
} //json str 转struct(部份字段)
var part Other
if err := json.Unmarshal([]byte(jsonStr), &part); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(part)
fmt.Println(part.SerTcpSocketPort)
} //struct 到json str
if b, err := json.Marshal(config); err == nil {
fmt.Println("================struct 到json str==")
fmt.Println(string(b))
} //map 到json str
fmt.Println("================map 到json str=====================")
enc := json.NewEncoder(os.Stdout)
enc.Encode(dat) //array 到 json str
arr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}
lang, err := json.Marshal(arr)
if err == nil {
fmt.Println("================array 到 json str==")
fmt.Println(string(lang))
} //json 到 []string
var wo []string
if err := json.Unmarshal(lang, &wo); err == nil {
fmt.Println("================json 到 []string==")
fmt.Println(wo)
}
}
//go post方式提交
//导入:"net/http" "crypto/tls" //调用片段: ////machineArry
jsonMachine, err := json.Marshal(machineArry)
if err == nil {
fmt.Println("================array 到 json str==")
fmt.Println(string(jsonMachine))
} //?link_token="+token_updatemachine
token_updatemachine :=beego.AppConfig.String("token_updatemachine") mappara :=map[string]interface{}{}
mappara["updateJson"]=string(jsonMachine)
mappara["link_token"]=token_updatemachine
masterUrl222 := beego.AppConfig.String("masterUrl") url222 := masterUrl222+"/cmdb/cmdbapi/updatemachine"
resmap :=this.HttpSendByJsonPost(url222,mappara) if resmap.(map[string]interface{})["code"].(string) =="000" {
return updatemap
}else{ updatemap["_code"] = "1"
updatemap["_msg"] = resmap.(map[string]interface{})["result"] return updatemap } func (this *BaseController) HttpSendByJsonPost(url string,formData map[string]interface{}) interface{} {
req := httplib.Post(url)
req.SetTransport(&http.Transport{DisableKeepAlives: true})
for k, v := range formData {
req.Param(k, v.(string))
}
req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
//req.Header("user", user)
//req.Header("role", role)
//req.SetHost()
var result interface{}
req.ToJson(&result) fmt.Println("resultresultresultresultresult:--------------->>>>>>>",result)
return result
}
golang的json操作的更多相关文章
- golang的json操作[转]
package main import ( "encoding/json" "fmt" "os" ) typ ...
- 48 【golang】json的效率
本文将主要做如下几方面的测试: 1,构造一个[100]struct的数组,然后来测试它的json编码后的字符串 或者([]byte),首先关心它的功能是否正常: 2,在很早之前,我们在使用golang ...
- Golang 处理 Json(二):解码
golang 编码 json 还比较简单,而解析 json 则非常蛋疼.不像 PHP 一句 json_decode() 就能搞定.之前项目开发中,为了兼容不同客户端的需求,请求的 content-ty ...
- Golang的json包
encoding/json encoding/json是官方提供的标准json, 实现RFC 7159中定义的JSON编码和解码.使用的时候需要预定义struct,原理是通过reflection和in ...
- Golang解析json的几种方法
Golang解析json的几种方法 概要 使用Golang调用其它平台API接口时总会被多层的json串给恶心到,我记录一下自己解析json的几种方法. 一.自带的json包 func JsonUnm ...
- Json操作(DynamicJson)
Json的简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了 ...
- ASP.NET 里的 JSON操作
最近项目中需要用到 JSON操作,google了一下 找到了几个比较好的操作方法.... 一 .使用 mircosoft 提供的 .NET Framework 自带的 json操作方法 1. 使用Ja ...
- Newtonsoft.Json 操作 JSON 字符串
Newtonsoft.Json介绍 在做开发的时候,很多数据交换都是以json格式传输的.而使用Json的时候,我们很多时候会涉及到几个序列化对象的使用:DataContractJsonSeriali ...
- Asp.Net Core 2.0 项目实战(8)Core下缓存操作、序列化操作、JSON操作等Helper集合类
本文目录 1. 前沿 2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装 3.XmlHelper快速操作xml文档 4.Serializatio ...
随机推荐
- MVC5-8 ViewData、ViewBag、TempData分析
MVC中Contoller与视图的数据传输 后台的值显示到界面上,我们有几种方式呢.MVC给我们提供了ViewData.ViewBag.TempData.Model这几种方式,当然我们也可以用ajax ...
- A.Kaw矩阵代数初步学习笔记 10. Eigenvalues and Eigenvectors
“矩阵代数初步”(Introduction to MATRIX ALGEBRA)课程由Prof. A.K.Kaw(University of South Florida)设计并讲授. PDF格式学习笔 ...
- [Android]关于Activity的InstanceState
Activity有两个方法onSaveInstanceState() 和 onRestoreInstanceState(). onSaveInstanceState()方法只适合用于保存一些临时性的状 ...
- OpenGLES入门笔记四
原文参考地址:http://www.cnblogs.com/zilongshanren/archive/2011/08/08/2131019.html 一.编译Vertex Shaders和Fragm ...
- ionic中获取坐标方法
ionic中获取坐标的方法 1.首相需要执行命令: cordova plugin add cordova-plugin-geolocation2.然后块级注入配置bower文件引入ngCordova ...
- mysql使用索引优化查询效率
索引的概念 索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针.更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度.在没 ...
- Matlab小技巧
记录一些用Matlab的技巧. //imshow全屏 subplot(1,3,3); imshow(topSketMat); hold on; set(gcf, 'units', 'normalize ...
- IEquatable 的Equals 代替 object 的Equals
struct Point2 : IEquatable<Point2> { public int X { get; set; } public int Y { get; set; } pub ...
- photobooth.js jquery
<div id="example" class="photobooth" style="width:758px;height:400px&quo ...
- 英文论文中i.e.,e.g.,etc.,viz.的简要小结
英文论文中i.e.,e.g.,etc.,viz.的简要小结 看了一堆用法,全白扯,自己总结的最好记,最实用 i.e. =即.换句话说.也就是说."'In essence' or 'in ot ...