dongmu9253
2016-12-06 05:10
浏览 290
已采纳

Golang将具有可变类型的json转换为字符串

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)
    }
}
}

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" }]

1条回答 默认 最新

相关推荐 更多相似问题