flat

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2023 License: MIT Imports: 2 Imported by: 0

README

Flat

Minimalistic implementation of the Flatten(map[string]interface{}) and Unflatten(map[string]interface{}) functions.

Description

Flatten converts the nested map into a flat map, where the keys are the paths to the values in the original map. The path is a dot-separated list of keys. The values are the values of the original map.

Unflatten converts the flat map into a nested map, where the keys are the paths to the values in the original map. The path is a dot-separated list of keys. The values are the values of the original map.

Both functions use javascript style to represent arrays in the path. For example, the path a.b[0].c will be converted into the following structure:

map[string]interface{}{
    "a": map[string]interface{}{
        "b": []interface{}{
            map[string]interface{}{
                "c": <value>,
            },
        },
    },
}

Usage


package main

import (
    "fmt"
    "github.com/illarion/flat"
    "encoding/json"
)

func main() {
    var src map[string]interface{}

    json.Parse([]byte(`{"a": {"b": [{"c": 1}, {"c": 2}]}}`), &src)

    flattened := flat.Flatten(src, &flat.Options{
        Delimiter: ".",
    })
    fmt.Sprintf("%#v", flattened)

    unflat := flat.Unflatten(flattened, &flat.Options{
        Delimiter: ".",
    })
    fmt.Sprintf("%#v", unflattened)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Flatten

func Flatten(input map[string]interface{}, opts *Options) map[string]interface{}

Flatten flattens a nested map[string]interface{} into a one level map[string]interface{}. The keys of the resulting map will be the path to the values in the nested map.

func Unflatten

func Unflatten(input map[string]interface{}, opts *Options) map[string]interface{}

Types

type Options

type Options struct {
	Delimiter string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL