dongzhuo1958 2017-07-01 10:46
浏览 87
已采纳

在Go中使用未知键值从JSON创建字符串映射

I try to create a map of strings from a JSON with an undefined number of unknow key-values.

Here is my example JSON file:

{
         "localhost":
        {
                "tag": "dev_latest",
                "vhost": "localhost.com"
        },
        "development":
        {
                "tag": "dev_latest",
                "vhost": "dev.com"
        }
}

I want to create a map[string]string with value like this:

config := map[string]string{
    "localhost-tag":      "dev_latest",
    "localhost-vhost": "localhost.com,
    "development-tag":   "dev_latest,
    ...
}

To parse a JSON with "github.com/jmoiron/jsonq" with known values, is quite easy, but in this case, localhost can be anything and tag can be any other thing.

My entry point in my Go code is like this:

func ParseJson(){
    configPath := GetConfigPath()
    b, err := ioutil.ReadFile(configPath) 

     //  Here, I need to create my map of strings..

    return configKeyStr

}

Any help will be really appreciate.

Thanks!

  • 写回答

3条回答 默认 最新

  • dongshushen4392 2017-07-01 11:00
    关注

    Easy to do. Simply convert.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    const s = `
    {
             "localhost":
            {
                    "tag": "dev_latest",
                    "vhost": "localhost.com"
            },
            "development":
            {
                    "tag": "dev_latest",
                    "vhost": "dev.com"
            }
    }
    `
    
    func main() {
        var m map[string]interface{}
        err := json.Unmarshal([]byte(s), &m)
        if err != nil {
            log.Fatal(err)
        }
        mm := make(map[string]string)
        for k, v := range m {
            mm[k] = fmt.Sprint(v)
        }
        fmt.Println(mm)
    }
    

    UPDATE

    Wrote flatten (maybe works as charm)

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "reflect"
    )
    
    const s = `
    {
             "localhost":
            {
                    "tag": "dev_latest",
                    "vhost": "localhost.com"
            },
            "development":
            {
                    "tag": "dev_latest",
                    "vhost": "dev.com"
            }
    }
    `
    
    func flatten(m map[string]interface{}) map[string]string {
        mm := make(map[string]string)
        for k, v := range m {
            switch reflect.TypeOf(v).Kind() {
            case reflect.Map:
                mv := flatten(v.(map[string]interface{}))
                for kk, vv := range mv {
                    mm[k+"-"+kk] = vv
                }
            case reflect.Array, reflect.Slice:
                for kk, vv := range m {
                    if reflect.TypeOf(vv).Kind() == reflect.Map {
                        mv := flatten(vv.(map[string]interface{}))
                        for kkk, vvv := range mv {
                            mm[k+"-"+kkk] = vvv
                        }
                    } else {
                        mm[k+"-"+kk] = fmt.Sprint(vv)
                    }
                }
            default:
                mm[k] = fmt.Sprint(v)
            }
        }
        return mm
    }
    
    func main() {
        var m map[string]interface{}
        err := json.Unmarshal([]byte(s), &m)
        if err != nil {
            log.Fatal(err)
        }
        b, _ := json.MarshalIndent(flatten(m), "", "  ")
        println(string(b))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀