Skip to content

accessor provides accessor for map/slice objects like json, yaml, toml etc.

License

Notifications You must be signed in to change notification settings

morikuni/accessor

Repository files navigation

accessor

Build Status GoDoc Go Report Card

accessor provides accessor for map/slice objects like json, yaml, toml etc.

Install

go get github.com/morikuni/accessor

Example

package main

import (
	"encoding/json"
	"log"
	"os"

	"github.com/morikuni/accessor"
)

func main() {
	text := `
	{
		"name": "morikuni",
		"friends": [
			{ "name": "hello" },
			{ "name": "world" }
		]
	}`

	var obj interface{}
	err := json.Unmarshal([]byte(text), &obj)
	if err != nil {
		log.Fatal(err)
	}

	acc, err := accessor.NewAccessor(obj)
	if err != nil {
		log.Fatal(err)
	}

	path, err := accessor.ParsePath("/friends")
	if err != nil {
		log.Fatal(err)
	}

	friends, err := acc.Get(path)
	if err != nil {
		log.Fatal(err)
	}

	err = friends.Foreach(func(path accessor.Path, value interface{}) error {
		return friends.Set(path, value.(string)+"_accessor")
	})
	if err != nil {
		log.Fatal(err)
	}

	err = json.NewEncoder(os.Stdout).Encode(acc.Unwrap())
	if err != nil {
		log.Fatal(err)
	}
}

will output

$ go run main.go | jq .
{
  "friends": [
    {
      "name": "hello_accessor"
    },
    {
      "name": "world_accessor"
    }
  ],
  "name": "morikuni"
}

About

accessor provides accessor for map/slice objects like json, yaml, toml etc.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages