Skip to content

berlincount/jsonstruct

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jsonstruct

Build Status Godoc license

A JSON deserializer for Go structures for Go 1.7+

Also visit Godoc.

Installation

go get -u github.com/berlincount/jsonstruct

Background

You are using Google's JSONAPI package with your Go web application and have a lot of structs in your database schema that you don't want to also have to implement as individual Go structures.

Introduction

jsonstruct uses StructOf to construct a Type which can be used to create Values which then can be used by other packages using reflection for structure discovery, like sqlx or GORM.

jsonstruct uses the following structures for descriptions:

type Field struct {
        Name      string            "json:\"name\""
        Type      string            "json:\"type\""
        Tags      reflect.StructTag "json:\"tags\""
}

type Struct struct {
        Struct string "json:\"struct\""
        Fields []Field
}

which allows e.g. to describe the example structures from JSON API using the following structure:

{"struct": "comment",
 "fields": [
  {"name": "ID",     "type": "int",    "tags": "jsonapi:\"primary,comments\""},
  {"name": "PostID", "type": "int",    "tags": "jsonapi:\"attr,post_id\""},
  {"name": "Body",   "type": "string", "tags": "jsonapi:\"attr,body\""}
]}
{"struct": "post",
 "fields": [
  {"name": "ID",       "type": "int", "tags": "jsonapi:\"primary,posts\""},
  {"name": "BlogID",   "type": "int", "tags": "jsonapi:\"attr,blog_id\""},
  {"name": "Title",    "type": "string", "tags": "jsonapi:\"attr,title\""},
  {"name": "Body",     "type": "string", "tags": "jsonapi:\"attr,body\""},
  {"name": "Comments", "type": "[]*comment", "tags": "jsonapi:\"relation,comments\""}
]}
{"struct": "blog",
 "fields": [
 {"name": "ID", "type": "int", "tags": "jsonapi:\"primary,blogs\""},
 {"name": "Title", "type": "string", "tags": "jsonapi:\"attr,title\""},
 {"name": "Posts", "type": "[]*post", "tags": "jsonapi:\"relation,posts\""},
 {"name": "CurrentPost", "type": "*post", "tags": "jsonapi:\"relation,current_post\""},
 {"name": "CurrentPostID", "type": "int", "tags": "jsonapi:\"attr,current_post_id\""},
 {"name": "CreatedAt", "type": "time.Time", "tags": "jsonapi:\"attr,created_at\""},
 {"name": "ViewCount", "type": "int", "tags": "jsonapi:\"attr,view_count\""}
]}

Example Apps

examples/jsonapi/jsonapi.go

examples/sqlx/sqlx.go

examples/gorm/gorm.go

These runnable files show using jsonstruct with JSON API as well as in conjunction with a database using sqlx or GORM.

You can use GB to build example binaries.

Contributing

Fork, Change, Pull Request with tests.

About

A JSON deserializer for Go structures for Go 1.7+

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages