Giter Site home page Giter Site logo

m-zajac / json2go Goto Github PK

View Code? Open in Web Editor NEW
131.0 4.0 17.0 5.45 MB

Create go type representation from json

Home Page: https://m-zajac.github.io/json2go

License: MIT License

Go 86.00% Makefile 1.97% HTML 12.04%
json-to-go json-to-golang json-to-struct json cli

json2go's Introduction

json2go Build Go Report Card GoDoc Coverage Mentioned in Awesome Go

Package json2go provides utilities for creating go type representation from json inputs.

Json2go can be used in various ways:

Why another conversion tool?

There are few tools for converting json to go types available already. But all of which I tried worked correctly with only basic documents.

The goal of this project is to create types, that are guaranteed to properly unmarshal input data. There are multiple test cases that check marshaling/unmarshaling both ways to ensure generated type is accurate.

Here's the micro acid test if you want to check this or other conversion tools:

[{"date":"2020-10-03T15:04:05Z","text":"txt1","doc":{"x":"x"}},{"date":"2020-10-03T15:05:02Z","_doc":false,"arr":[[1,null,1.23]]},{"bool":true,"doc":{"y":123}}]

And correct output with some comments:

type Document []struct {
        Arr  [][]*float64 `json:"arr,omitempty"` // Should be doubly nested array; should be a pointer type because there's null in values.
        Bool *bool        `json:"bool,omitempty"` // Shouldn't be `bool` because when key is missing you'll get false information.
        Date *time.Time   `json:"date,omitempty"` // Could be also `string` or `*string`.
        Doc  *struct {
                X *string `json:"x,omitempty"` // Should be pointer, because key is not present in all documents.
                Y *int    `json:"y,omitempty"` // Should be pointer, because key is not present in all documents.
        } `json:"doc,omitempty"` // Should be pointer, because key is not present in all documents in array.
        Doc2 *bool   `json:"_doc,omitempty"` // Attribute for "_doc" key (other that for "doc"!). Type - the same as `Bool` attribute.
        Text *string `json:"text,omitempty"` // Could be also `string`.
}

CLI Installation

go get github.com/m-zajac/json2go/...

Usage

Json2go can be used as cli tool or as package.

CLI tools can be used directly to create go type from stdin data (see examples).

Package provides Parser, which can consume multiple jsons and outputs go type fitting all inputs (see examples and documentation). Example usage: read documents from document-oriented database and feed them too parser for go struct.

CLI usage examples

echo '{"x":1,"y":2}' | json2go

curl -s https://api.punkapi.com/v2/beers?page=1&per_page=5 | json2go

Check this one :)


cat data.json | json2go

Package usage examples

inputs := []string{
	`{"x": 123, "y": "test", "z": false}`,
	`{"a": 123, "x": 12.3, "y": true}`,
}

parser := json2go.NewJSONParser("Document")
for _, in := range inputs {
	parser.FeedBytes([]byte(in))
}

res := parser.String()
fmt.Println(res)

Example outputs

{
    "line": {
        "point1": {
            "x": 12.1,
            "y": 2
        },
        "point2": {
            "x": 12.1,
            "y": 2
        }
    }
}
type Document struct {
        Line struct {
                Point1 Point `json:"point1"`
                Point2 Point `json:"point2"`
        } `json:"line"`
}
type Point struct {
        X float64 `json:"x"`
        Y int     `json:"y"`
}

[
    {
        "name": "water",
        "type": "liquid",
        "boiling_point": {
            "units": "C",
            "value": 100
        }
    },
    {
        "name": "oxygen",
        "type": "gas",
        "density": {
            "units": "g/L",
            "value": 1.429
        }
    },
    {
        "name": "carbon monoxide",
        "type": "gas",
        "dangerous": true,
        "boiling_point": {
            "units": "C",
            "value": -191.5
        },
        "density": {
            "units": "kg/m3",
            "value": 789
        }
    }
]
type Document []struct {
        BoilingPoint *UnitsValue `json:"boiling_point,omitempty"`
        Dangerous    *bool       `json:"dangerous,omitempty"`
        Density      *UnitsValue `json:"density,omitempty"`
        Name         string      `json:"name"`
        Type         string      `json:"type"`
}
type UnitsValue struct {
        Units string  `json:"units"`
        Value float64 `json:"value"`
}

Contribution

I'd love your input! Especially reporting bugs and proposing new features.

json2go's People

Contributors

m-zajac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

json2go's Issues

Output to type Name struct

How do we use a *JSONParser as a type struct without copying and pasting the .string ??? I.e. define a struct with the output of parser.FeedValue() without having to copy and pee.

Incorrect struct type

The struct type is incorrectly created for the newly created datatype. The newly datatype is created as an array struct when one of the extractable substructure is an array at one place and non-array in other.

Input
{"starttime":"2021-03-10T08:04:05Z", "endtime":"2021-03-10T15:04:05Z", "details": [{"state":"working", "duration":25 }, {"state":"idle", "duration":15 }, {"state":"working", "duration":20 }] },
{"starttime":"2021-03-10T08:04:05Z", "endtime":"2021-03-10T15:04:05Z", "totalwork": {"state":"working", "duration":25 } },

Ouput
Expected
type Document struct {
Details []DurationState json:"details,omitempty"
Endtime time.Time json:"endtime"
Starttime time.Time json:"starttime"
Totalwork *DurationState json:"totalwork,omitempty"
}
type DurationState struct {
Duration int json:"duration"
State string json:"state"
}

Actual
type Document struct {
Details []DurationState json:"details,omitempty"
Endtime time.Time json:"endtime"
Starttime time.Time json:"starttime"
Totalwork *DurationState json:"totalwork,omitempty"
}
type DurationState []struct {
Duration int json:"duration"
State string json:"state"
}

Here the DurationState is created as an array struct when it should just be a struct.

I am willing to provide a PR for this issue with fix. Please let me know.

Nested arrays parsing error

package main

import (
	"fmt"

	"github.com/m-zajac/json2go"
)

func main() {
	arrSInp := []string{
		`[[{"a": 2, "b": 3}, {"a": 4, "b": 5}]]`,
		`[[{"a":6, "b": 7}, {"a": 8, "b": 9}]]`,
	}
  
	parser := json2go.NewJSONParser("X")
	for _, in := range arrSInp {
		parser.FeedBytes([]byte(in))
	}
	fmt.Println(parser.String())
}

want:

  type X [][]struct {
          A       int     `json:"a"`
          B       int     `json:"b"`
  }

got:

  type X []struct {
          A       int     `json:"a"`
          B       int     `json:"b"`
  }

Invalid output for some inputs

Examples to check:

[1, 2, 3.1]
{
"_id":123,
"id":123
}
{
"i":"sda",
"i":1
}
{
  "test\"`\n}\n \nfunc init() {\n panic(\"\")\nvar test = `\"": 123
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.