Golang将带有变量类型的json转换为字符串

编程入门 行业动态 更新时间:2024-10-10 12:19:43
本文介绍了Golang将带有变量类型的json转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从API响应中读取json,我遇到了一个问题,即json值(strings,null,bool)中有多种数据类型。此外,某些键的值可以是字符串或null,这使得将数据读入类型变得更加困难。我想将所有内容转换为字符串以便于处理。我基于google搜索其他示例创建了一个类型开关。我想知道这是否是最简单的方法,或者我错过了一个更简单的方法。

I am reading in json from an API response and I ran into an issue in that there are multiple data types inside the json values (strings, null, bool). In addition, some keys have values which can be either a string or null which makes reading the data into types more difficult. I want to convert everything to strings for ease of handling. I created a type switch based on googling other examples. I am wondering if this is the easiest way to do this or if I am missing a simpler approach.

package main import ( "encoding/json" "fmt" "strconv" ) func main() { json_byte := []byte(`{"response":[{"t_int":1, "t_bool": true, "t_null_or_string": null}, {"t_int":2, "t_bool": false, "t_null_or_string": "string1"}]}`) //unmarshal the json to data structure using interface for variable data types data_json := make(map[string][]map[string]interface{}) //create a structure to hold unmarshalled json if err := json.Unmarshal(json_byte, &data_json); err != nil { panic(err) } fmt.Println("json_data: ", data_json) //Iterate over data structure and convert Bool, Int, and Null types to string var v_conv string // temporary holding for converted string values data_map := make(map[string]string) // temporary holding for converted maps data_final := make([]map[string]string, 0, 100) // final holding for data converted to strings for _, v := range data_json { //v is the value of the "response": key which is a slice of maps for _, v2 := range v { //v2 is one of the maps in the slice of maps for k3, v3 := range v2 { //k3 and v3 are the keys and values inside the map fmt.Println("k3: ", k3, "v3: ", v3) switch v_type := v3.(type) { case nil: v_conv = "" case bool: v_conv = strconv.FormatBool(v3.(bool)) case int: v_conv = strconv.Itoa(v3.(int)) case string: v_conv = v3.(string) case float64: v_conv = strconv.FormatFloat(v3.(float64), 'f', 0, 64) default: fmt.Println("vtype unknown: ", v_type) //have to use v_type since it is declared v_conv = "" } data_map[k3] = v_conv //append a new map key/value pair both as strings fmt.Println("data_map: ", data_map) } data_final = append(data_final, data_map) // after each cycle through the loop append the map to the new list fmt.Println("data_final: ", data_final) } } }

最终格式需要一张地图 [{t_int:1,t_bool:true,t_null_string:}, { t_int:2,t _bool:false,t_null_string:string1}]

Final Format Desired a Slice of Maps [{ "t_int": "1", "t_bool": "true", "t_null_string": "" }, { "t_int": "2", "t_bool": "false", "t_null_string": "string1" }]

推荐答案

这个答案我假设您的示例中的JSON是您的JSON输入(的一部分)的示例。 在这种情况下,您的JSON具有特定的结构:您知道哪些属性带有已知数据类型,并且您知道哪些属性是动态的。 例如,您可以将您的JSON解组为smth,如下面的ResponseObj:

For this answer I'm assuming that JSON in your example is an example of (part of) your JSON input. In this case, your JSON has a specific structure: you know which attributes are coming with a known data type and also you know which attributes a dynamic. For example, you could unmarshal your JSON into smth like ResponseObj below:

package main import ( "encoding/json" "fmt" ) type ResponseObj struct { Response []Item `json:"response"` } type Item struct { TInt int `json:"t_int"` TBool bool `json:"t_bool"` TMixed interface{} `json:"t_null_or_string"` } func main() { json_byte := []byte(`{"response":[{"t_int":1, "t_bool": true, "t_null_or_string": null}, {"t_int":2, "t_bool": false, "t_null_or_string": "string1"}]}`) data_json := ResponseObj{} if err := json.Unmarshal(json_byte, &data_json); err != nil { panic(err) } fmt.Printf("%+v\n", data_json) }

您的数据将如下所示:

{ Response: [ { TInt:1 TBool:true TMixed:<nil> } { TInt:2 TBool:false TMixed:string1 } ] }

是的,对于具有混合类型的属性,您将运行类型断言(或与您的nil进行比较)或者两者兼而有之。)

And yes, for an attribute with a mixed type you'll run a type assertion (or comparison with nil as in your case or both).

不太可能你的JSON是不可预测类型的混乱。最有可能的是,您可以单独输出核心结构,并使用接口{}作为剩余的混合类型。

Unlikely your JSON is a total chaos of unpredictable types. Most likely, you can single out a core structure and use interface{} for remaining, mixed types.

希望这会有所帮助。

更多推荐

Golang将带有变量类型的json转换为字符串

本文发布于:2023-07-31 22:31:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1262770.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   变量   类型   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!