All Projects → danhper → Structomap

danhper / Structomap

Licence: mit
Easily and dynamically generate maps from Go static structures

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Structomap

Quicklib
Quick development library (AutoMapper, LinQ, IOC Dependency Injection, MemoryCache, Scheduled tasks, Config, Serializers, etc) with crossplatform support for Delphi/Firemonkey (Windows,Linux,OSX/IOS/Android) and freepascal (Windows/Linux).
Stars: ✭ 274 (+124.59%)
Mutual labels:  json, serializer
Acts as api
makes creating API responses in Rails easy and fun
Stars: ✭ 506 (+314.75%)
Mutual labels:  json, serializer
Gosercomp
⚡️ Golang Serializer Benchmark Comparison
Stars: ✭ 300 (+145.9%)
Mutual labels:  json, serializer
Rdflib Jsonld
JSON-LD parser and serializer plugins for RDFLib (Python 2.6+)
Stars: ✭ 250 (+104.92%)
Mutual labels:  json, serializer
Servicestack.text
.NET's fastest JSON, JSV and CSV Text Serializers
Stars: ✭ 1,157 (+848.36%)
Mutual labels:  json, serializer
Play Json
The Play JSON library
Stars: ✭ 254 (+108.2%)
Mutual labels:  json, serializer
Tomlplusplus
Header-only TOML config file parser and serializer for C++17 (and later!).
Stars: ✭ 403 (+230.33%)
Mutual labels:  json, serializer
Deepkit Framework
A new full-featured and high-performance web framework for sophisticated Typescript projects like complex admin interfaces, websites, games, desktop and mobile apps.
Stars: ✭ 307 (+151.64%)
Mutual labels:  json, serializer
Dictfier
Python library to convert/serialize class instances(Objects) both flat and nested into a dictionary data structure. It's very useful in converting Python Objects into JSON format
Stars: ✭ 67 (-45.08%)
Mutual labels:  json, serializer
Eminim
JSON serialization framework for Nim, works from a Stream directly to any type and back. Depends only on stdlib.
Stars: ✭ 32 (-73.77%)
Mutual labels:  json, serializer
Pxi
🧚 pxi (pixie) is a small, fast, and magical command-line data processor similar to jq, mlr, and awk.
Stars: ✭ 248 (+103.28%)
Mutual labels:  json, serializer
Java
jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
Stars: ✭ 1,308 (+972.13%)
Mutual labels:  json, serializer
Jsonapi Utils
Build JSON API-compliant APIs on Rails with no (or less) learning curve.
Stars: ✭ 191 (+56.56%)
Mutual labels:  json, serializer
Surrealist
to_json but I wrote it myself
Stars: ✭ 271 (+122.13%)
Mutual labels:  json, serializer
Serializer
With the Serializer component it's possible to handle serializing data structures, including object graphs, into array structures or other formats like XML and JSON. It can also handle deserializing XML and JSON back to object graphs.
Stars: ✭ 2,021 (+1556.56%)
Mutual labels:  json, serializer
Blueprinter
Simple, Fast, and Declarative Serialization Library for Ruby
Stars: ✭ 623 (+410.66%)
Mutual labels:  json, serializer
Go
A high-performance 100% compatible drop-in replacement of "encoding/json"
Stars: ✭ 10,248 (+8300%)
Mutual labels:  json, serializer
Symfony Jsonapi
JSON API Transformer Bundle for Symfony 2 and Symfony 3
Stars: ✭ 114 (-6.56%)
Mutual labels:  json, serializer
Config Lint
Command line tool to validate configuration files
Stars: ✭ 118 (-3.28%)
Mutual labels:  json
Typedload
Python library to load dynamically typed data into statically typed data structures
Stars: ✭ 120 (-1.64%)
Mutual labels:  json

structomap Build Status Coverage Status GoDoc

This package helps you to transform your struct into map easily. It provides a structomap.Serializer interface implemented by the structomap.Base type which contains chainable function to add, remove or modify fields. The struct is transformed to a map[string]interface{} using the Transform(entity interface{}) method. It is then up to you to encode the result in JSON, XML or whatever you like.

Here is an example.

import "github.com/danhper/structomap"

type User struct {
    ID        int
    Email     string
    HideEmail bool
    FirstName string
    LastName  string
    CreatedAt time.Time
    UpdatedAt time.Time
}

currentTime := time.Date(2015, 05, 13, 15, 30, 0, 0, time.UTC)

user := User{
    ID: 1, Email: "[email protected]", FirstName: "Foo", LastName:  "Bar",
    HideEmail: true, CreatedAt: currentTime, UpdatedAt: currentTime,
}
userSerializer := structomap.New().
              UseSnakeCase().
              Pick("ID", "FirstName", "LastName", "Email").
              PickFunc(func(t interface{}) interface{} {
                  return t.(time.Time).Format(time.RFC3339)
              }, "CreatedAt", "UpdatedAt").
              OmitIf(func(u interface{}) bool {
                  return u.(User).HideEmail
              }, "Email").
              Add("CurrentTime", time.Date(2015, 5, 15, 17, 41, 0, 0, time.UTC)).
              AddFunc("FullName", func(u interface{}) interface{} {
                  return u.(User).FirstName + " " + u.(User).LastName
              })

userMap := userSerializer.Transform(user)
str, _ := json.MarshalIndent(userMap, "", "  ")
fmt.Println(string(str))

will give:

{
  "created_at": "2015-05-13T15:30:00Z",
  "current_time": "2015-05-15T17:41:00Z",
  "first_name": "Foo",
  "full_name": "Foo Bar",
  "id": 1,
  "last_name": "Bar",
  "updated_at": "2015-05-13T15:30:00Z"
}

Working with slices and arrays

You can also use structomap to transform slices and arrays, it will be applied to all elements. The only thing to do is to call TransformArray(entities) on a slice or an array. As TransformArray expects an interface{}, but in fact really wants a slice or an array, a second error argument is returned. If you do not want it, you can use MustTransformArray, which will panic instead of returning an error.

Here in an example reusing the above serializer.

otherUser := User{ID: 2, FirstName: "Ping", LastName: "Pong", CreatedAt: createdAt, UpdatedAt: createdAt}
users := []User{user, otherUser}
result, _ := userSerializer.TransformArray(users)
str, _ := json.MarshalIndent(result, "", "  ")
fmt.Println(string(str))

This will give:

[
  {
    "created_at": "2015-05-13T15:30:00Z",
    "current_time": "2015-05-15T17:41:00Z",
    "first_name": "Foo",
    "full_name": "Foo Bar",
    "id": 1,
    "last_name": "Bar",
    "updated_at": "2015-05-13T15:30:00Z"
  },
  {
    "created_at": "2015-05-13T15:30:00Z",
    "current_time": "2015-05-15T17:41:00Z",
    "email": "",
    "first_name": "Ping",
    "full_name": "Ping Pong",
    "id": 2,
    "last_name": "Pong",
    "updated_at": "2015-05-13T15:30:00Z"
  }
]

Choosing a key format

You can set the key format for the output map using UseSnakeCase(), UsePascalCase() or UseCamelCase() on the serializer object. You can also set the default case for all new serializers by using structomap.SetDefaultCase(structomap.SnakeCase) (structomap.CamelCase and structomap.PascalCase are also available). The init() function would be a good place to set this.

Building your own serializer

With structomap.Base as a base, you can easily build your serializer.

type UserSerializer struct {
  *structomap.Base
}

func NewUserSerializer() *UserSerializer {
  u := &UserSerializer{structomap.New()}
  u.Pick("ID", "CreatedAt", "UpdatedAt", "DeletedAt")
  return u
}

func (u *UserSerializer) WithPrivateInfo() *UserSerializer {
  u.Pick("Email")
  return u
}

userMap := NewUserSerializer().WithPrivateInfo().Transform(user)

Note that the u.Pick, and all other methods do modify the serializer, they do not return a new serializer each time. This is why it works even when ignoring u.Pick return value.

License

This is released under the MIT license. See the LICENSE file for more information.

Godoc

The full documentation is available at https://godoc.org/github.com/danhper/structomap.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].