gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:38:31 27 4
gpt4 key购买 nike

目前我正在使用以下代码将嵌套的 json 转换为扁平化的 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,但是我做不到。

我最接近的猜测是嵌套 map 的使用,但我不知道如何创建具有 N 级的嵌套 map 。

编辑:我需要这个的原因:我将数据存储在 Redis 中,如果我将 json 存储到 Redis 中,那么我将无法搜索键,这就是我将键转换为 key1:key2:key3 的原因:一些_值

最佳答案

为了“展开”数据,您需要在点处拆分每个键并创建嵌套对象。 Here is an example在 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 转换为嵌套的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46405557/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com