本文介绍了将扁平化的json转换为嵌套的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用以下代码将嵌套的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)
}

这是输出:{"person.address.street":"123 Main St.","person.name":"Joe"}

经过一些处理后,现在我想将此数据还原到普通的嵌套json中,但是我无法这样做.

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

我最接近的猜测是嵌套地图的使用,但是我不知道如何创建具有N个级别的嵌套地图.

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

我需要这样做的原因:我将数据存储在Redis中,如果我将json存储到Redis中,那么我将无法搜索键,这就是为什么我将键转换为key1:key2:key3: some_value

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

推荐答案

为了展开"数据,您需要在点处拆分每个键并创建嵌套对象. 这里是一个示例,其中包含您在Go Playground上的数据.

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 
} 

这篇关于将扁平化的json转换为嵌套的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:54