flatmap

package
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2024 License: Apache-2.0 Imports: 4 Imported by: 1

Documentation

Overview

Package flatmap contains functions to flatten and unflatten maps:

  • Do flattens a nested map into a flat map.
  • Undo unflattens a flat map into a nested map.

The flattening follows the JSONPath standard.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do(nested map[string]any) map[string]any

Do takes a nested map and flattens it into a single level map. The flattening follows the JSONPath standard. Please see the example to understand how the flattened output looks like.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/nextmv-io/sdk/flatmap"
)

func main() {
	nested := map[string]any{
		"a": "foo",
		"b": []any{
			map[string]any{
				"c": "bar",
				"d": []any{
					map[string]any{
						"e": 2,
					},
					true,
				},
			},
			map[string]any{
				"c": "baz",
				"d": []any{
					map[string]any{
						"e": 3,
					},
					false,
				},
			},
		},
	}

	flattened := flatmap.Do(nested)

	b, err := json.MarshalIndent(flattened, "", "  ")
	if err != nil {
		panic(err)
	}

	fmt.Println(string(b))

}
Output:

{
  "$.a": "foo",
  "$.b[0].c": "bar",
  "$.b[0].d[0].e": 2,
  "$.b[0].d[1]": true,
  "$.b[1].c": "baz",
  "$.b[1].d[0].e": 3,
  "$.b[1].d[1]": false
}

func Undo

func Undo(flattened map[string]any) (map[string]any, error)

Undo takes a flattened map and nests it into a multi-level map. The flattened map should follow the JSONPath standard. Please see the example to understand how the nested output looks like.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/nextmv-io/sdk/flatmap"
)

func main() {
	flattened := map[string]any{
		"$.a":           "foo",
		"$.b[0].c":      "bar",
		"$.b[0].d[0].e": 2,
		"$.b[0].d[1]":   true,
		"$.b[1].c":      "baz",
		"$.b[1].d[0].e": 3,
		"$.b[1].d[1]":   false,
	}

	nested, err := flatmap.Undo(flattened)
	if err != nil {
		panic(err)
	}

	b, err := json.MarshalIndent(nested, "", "  ")
	if err != nil {
		panic(err)
	}

	fmt.Println(string(b))
}
Output:

{
  "a": "foo",
  "b": [
    {
      "c": "bar",
      "d": [
        {
          "e": 2
        },
        true
      ]
    },
    {
      "c": "baz",
      "d": [
        {
          "e": 3
        },
        false
      ]
    }
  ]
}

Types

This section is empty.

Jump to

Keyboard shortcuts

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