dp13668681869 2017-09-25 12:43
浏览 425
已采纳

将扁平化的json转换为嵌套的json

Currently I'm using the following code to convert nested json into flattened json:

import (
    "fmt"

    "github.com/nytlabs/gojsonexplode"
)
func main() {
    input := `{"person":{"name":"Joe", "address":{"street":"123 Main St."}}}`
    out, err := gojsonexplode.Explodejsonstr(input, ".")
    if err != nil {
        // handle error
    }
    fmt.Println(out)
}

This is the output: {"person.address.street":"123 Main St.","person.name":"Joe"}

After some processing, now I want to restore this data into normal nested json, but I'm unable to do so.

My closest guess is usage of nested maps, but I don't know how to create nested map with N levels.

EDIT: Reason why I need this: I'm storing data in Redis, and if I store json into Redis then I can't search for keys, that's why I convert keys into key1:key2:key3: some_value

  • 写回答

2条回答 默认 最新

  • dongxun2089 2017-09-25 14:17
    关注

    In order to "unflatten" the data you need to split each of the keys at the dot and create nested objects. Here is an example with your data on the Go Playground.

    func unflatten(flat map[string]interface{}) (map[string]interface{}, error) {
        unflat := map[string]interface{}{}
    
        for key, value := range flat {
            keyParts := strings.Split(key, ".")
    
            // Walk the keys until we get to a leaf node.
            m := unflat
            for i, k := range keyParts[:len(keyParts)-1] {
                v, exists := m[k]
                if !exists {
                    newMap := map[string]interface{}{}
                    m[k] = newMap
                    m = newMap
                    continue
                }   
    
                innerMap, ok := v.(map[string]interface{})
                if !ok {
                    return nil, fmt.Errorf("key=%v is not an object", strings.Join(keyParts[0:i+1], "."))
                }   
                m = innerMap
            }   
    
            leafKey := keyParts[len(keyParts)-1]
            if _, exists := m[leafKey]; exists {
                return nil, fmt.Errorf("key=%v already exists", key)
            }   
            m[keyParts[len(keyParts)-1]] = value
        }   
    
        return unflat, nil 
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?
  • ¥15 C#连接不上服务器,