Code Monkey home page Code Monkey logo

json-to-go's Introduction

JSON-to-Go converts JSON to a Go struct

Translates JSON into a Go type definition. Check it out!

This is a sister tool to curl-to-Go, which converts curl commands to Go code.

Things to note:

  • The script sometimes has to make some assumptions, so give the output a once-over.
  • In an array of objects, it is assumed that the first object is representative of the rest of them.
  • The output is indented, but not formatted. Use go fmt!

Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.

Credits

JSON-to-Go is brought to you by Matt Holt (mholt6).

The Go Gopher is originally by Renee French. This artwork is an adaptation.

json-to-go's People

Contributors

anpez avatar apxamccallum avatar brock-weaver-roostify avatar ejcx avatar hajimehoshi avatar hirochachacha avatar jacobbednarz avatar jheimbach avatar kkkiio avatar mbc avatar mholt avatar mike-hosseini avatar netaisllc avatar relistan avatar remitly-brandonr avatar sarathsp06 avatar shevaxu avatar wvell avatar yanpozka avatar yaroslavpodorvanov 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  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

json-to-go's Issues

Web version does not work

Hi there,
https://mholt.github.io/json-to-go/
Does not works (it ommits declarations like this:)

type AutoGenerated struct {
	Status int `json:"status"`
	Result struct {
		TotalCount  `json:"totalCount"`
		CurrentPage `json:"currentPage"`
		PageSize    `json:"pageSize"`
		Items       []struct {
			Values     `json:"values"`
			Properties []struct {
				Name       `json:"name"`
				Type       `json:"type"`
				Multiple   `json:"multiple"`
				Title      `json:"title"`
				Constraint `json:"constraint"`
				Value      `json:"value"`
				LongValue  `json:"longValue"`
				Link       `json:"link"`
				Mime       `json:"mime"`
			} `json:"properties"`
			ID          `json:"id"`
			AlfrescoID  `json:"alfrescoId"`
			NodeRef     `json:"nodeRef"`
			Type        `json:"type"`
			Permissions `json:"permissions"`
		} `json:"items"`
	} `json:"result"`
	Message interface{} `json:"message"`
	Trace   interface{} `json:"trace"`
}

no issue; just thanks

brilliant work!
I was absolutely not looking forward to generate struct for this super complicated JSON api

Thanks a lot for publishing this, it made my day.

Handle arbritrary keys

First off thanks for making this tool. I've used it on several projects. One issue I've bumped into a few times now is:

Some services, use JSON where the keys are arbitrarily generated. Here is an example where I handle this in my own code.

Sample JSON input

{
    "status": "success",
    "response": {
        "12345678": {
            "dynamic": true,
            "label": "My Label One",
            "ip_address": "11.222.123.124"
        },
         "22345678": {
            "dynamic": false,
            "label": "My Label two",
            "ip_address": "11.222.123.124"
        }
    }
}

In this case the keys "22345678" and "12345678" are dynamic. I am not a fan of this sort of data structure and would much prefer if they would have used an array. But I have no control over this third-party service.

It would be nice if there were a way to give a hint to json-to-go so it would generate that as a map with a given object value.

Current Output

type AutoGenerated struct {
	Status   string `json:"status"`
	Response struct {
		Num12345678 struct {
			Dynamic   bool   `json:"dynamic"`
			Label     string `json:"label"`
			IPAddress string `json:"ip_address"`
		} `json:"12345678"`
		Num22345678 struct {
			Dynamic   bool   `json:"dynamic"`
			Label     string `json:"label"`
			IPAddress string `json:"ip_address"`
		} `json:"22345678"`
	} `json:"response"`
}

Preferred Output

It would be much better if the resulting structs would do something like this instead:

Response     map[string]NetworkObject `json:"response"` 
type NetworkObject struct {
	Dynamic   bool   `json:"dynamic"`
	Label     string `json:"label"`
	IPAddress string `json:"ip_address"`
}

type NetworksResponse struct {
	Status       string                   `json:"status"`
	Response     map[string]NetworkObject `json:"response"`
	Error        int                      `json:"error"`
	ErrorMessage string                   `json:"error_message"`
}

Solution

With all this said I am not quite sure how to provide this sort of hint to json-to-go. Maybe could use special key names or potentially provide a JSON array that contains a list of keys what should invoke this sort of behavior.

Maybe something like this "json2go_dynamic_keys":["12345678", "22345678"], so the resulting input json would be this:

{
   "json2go_dynamic_keys":["12345678", "22345678"],
    "status": "success",
    "response": {
        "12345678": {
            "dynamic": true,
            "label": "My Label One",
            "ip_address": "11.222.123.124"
        },
         "22345678": {
            "dynamic": false,
            "label": "My Label two",
            "ip_address": "11.222.123.124"
        }
    }
}

This is awesome

No issue to report, just want to say thanks for releasing this project. This thing is awesome, super helpful. Saved me a bunch of time.

Error parsing [][]string structure

Hi,

The following JSON is parsed incorrectly when NOT using inline structures:

{
  "assigned_to": 7,
  "tags": [
    [
      "hello",
      "#ab14d9"
    ]
  ]
}

When using inline structures, it's converted as expected:

type AutoGenerated struct {
	AssignedTo int        `json:"assigned_to"`
	Tags       [][]string   `json:"tags"`
}

When NOT using inline structures, parsing fails:

3:13: expected ';', found '[' (and 1 more errors)

It should return something like:

type Tags [][]string
type AutoGenerated struct {
	AssignedTo int        `json:"assigned_to"`
	Tags       Tags          `json:"tags"`
}

Thanks for the awesome tool!

Support huge JSON inputs

After fixing #6, it might be worth adding file processing support.

It would work by selecting a .json file and then processing it in a streaming fashion. This would allow super-huge JSON inputs to be processed successfully.

I've done huge file processing in the browser before with Papa Parse. The easy part (that is most useful) is loading the file in pieces -- the hard part is parsing the JSON in pieces. Will need to look into this.

Named types fails on arrays of objects

Hello! Thanks for this great tool. I tried out the new non-anonymous structs feature and noticed a bug so I thought to let you know.

When you have an object that has a field which is an array of objects the generator fails. For example, this input:

{
  "users": [
    {
      "name": "Gopher"
    }
  ]
}

When used with the classic behavior it works fine. When I uncheck the box so I get two separate types I instead get this

2:11: expected type, found 'STRING' `json:"users"`

json decode to struct isn't correct?

this is json data from ElasticSearch.

{
    "_source": {
        "excludes": [
            "offset",
            "*type",
            "beat",
            "*timestamp"
        ]
    },
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "loglvl.keyword": "ERROR"
                    }
                },
                {
                    "term": {
                        "module": "demo"
                    }
                },
                {
                    "range": {
                        "logtime": {
                            "gte": "2017-10-20T09:45:35.015+0800",
                            "lte": "2017-10-24T09:45:35.015+0800"
                        }
                    }
                }
            ]
        }
    }
}

result is missing query.bool.filter.term.module.the first term is ok. The two term can't combine because of Elasticsearch's syntax.

can json-to-go convert without nest struct

{
"a":{
"b":{
"c":"d"
}
}
}

json-to-go will convert json to under:

type AutoGenerated struct {
	A struct {
		B struct {
			C string `json:"c"`
		} `json:"b"`
	} `json:"a"`
}

can json-to-go convert like this without nest struct?

type AutoGeneratedAB struct {
	C string `json:"c"`
}
type AutoGeneratedA struct {
	B AutoGeneratedAB `json:"b"`
}
type AutoGenerated struct {
	A  AutoGeneratedA `json:"a"`
}

Features and Ideas

Hey there,

First I want to thank you for creating this generator, was a big help.

Secondly, I have created my own implementation of this in php here: dcarbone/json-to-go

I added a few features I needed for various projects, namely:

  • Convert simple type (string, int, float, bool) literals into pointers. This is helpful when you need to need to have a trinary state for simple type properties:
    • Populated, non-zero (true)
    • Populated, zero (false)
    • Actually empty (nil)
  • Break out nested structs, slices, and maps into separate types
    • Lots of uses, primarily useful when constructing type or using nested type as argument / return type, etc.
  • Force ",omitempty" onto everything
    • In conjunction with the aforementioned "pointer" stuff, this can be used to prevent unspecified-but-interpreted zero-val values from causing havoc on upstream API's
  • Force int -> float
    • Because js ints are a lie
  • Force empty structs to interface{}
    • This can be useful if the example JSON payload has a "{}" in it somewhere, indicating that the response is an object but not giving you specifics.
  • Custom callbacks on certain actions. I elected to allow the following to be overloaded:
    • goType: Returns string representation of the go type (struct, slice, interface, etc.). By default my parser, like yours, does not do any sort of "map" or "json.RawMessage" determination as it is impossible to accurately do this automatically. Instead I let the user overload the "type" determination. "map" will lead to a specific type (MapType) while "json.RawMessage" and others will attempt to be created as SimpleType'd items. I might flesh this out if need be.
    • mostSpecificPossibleGoType: I only check for float / int determination, but I'm sure others have more advanced needs.
    • formatPropertyName: I follow your property name formatting system very closely, but I figure let others implement their own formatter if they need
    • toProperCase: Again, I follow your implementation on this but others might want to muck with it.

My use cases for the above generally revolve around mapping request and response types for large api's (hundreds of separate endpoints, which can lead to over a thousand separate models), and wanting to generate them on the fly.

I am not sure how many of these features would be helpful to the world at large, but I wanted to see if any would be of interest to you, and possibly provide ideas for future development.

If one stands out, let me know and I can work on a PR for your JS version.

Thanks again!
- Daniel

type of element array

json:

{
"float-array":[0.1, 2.4, 3]
}

result:

type AutoGenerated struct {
FloatArray []int json:"float-array"
}

Clear button and Copy button

I love your tool - I've been using it a lot recently!

My work flow generally is copy some bit of javascript, go to the tool, realise that it has the last bit of javascript I put in already there and click refresh. A clear button on the left hand side to clear the left hand form would be very useful in this situation.

Likewise a copy button on the right hand side to copy the output of the RHS text box into the copy buffer would save me time too!

Thanks for a great tool

Nick

Rename to "Takeout"

This is just a memo to self.

Subtitle will be "JSON to Go", from current title.

Handle cases where json.RawMessage should be used instead.

So in my code I have a config file in the form of

{
    "destinations": [
        {
            "username": "Catgirls are sexy",
            "avatar": "https://b.catgirlsare.sexy/xik9.png",
            "webhook": "your discord webhook url goes here",
            "cron": "0/5 * * * * *",
            "sources": [
                {
                    "service": "randomcat",
                    "chance": 1,
                    "arguments": {"something": "different"}
                },
                {
                    "service": "ibsearch",
                    "chance": 2,
                    "arguments": {"query": "nekomimi rating:safe random: size:<2m>1m", "key": "ibsearch key goes here"}
                },
                {
                    "service": "ibsearch",
                    "chance": 2,
                    "arguments": {"query": "fox_ears rating:safe random: size:<2m>1m", "key": "ibsearch key goes here"}
                }
            ] 
        }
    ]
}

The point here is, each source is handled by it's service, those in turn may opt in to read optional arguments from it's definition. Which you can see for ibsearch I have defined.
What I get when I run this through your tool is I get

type AutoGenerated struct {
	Destinations []struct {
		Username string `json:"username"`
		Avatar string `json:"avatar"`
		Webhook string `json:"webhook"`
		Cron string `json:"cron"`
		Sources []struct {
			Service string `json:"service"`
			Chance int `json:"chance"`
			Arguments struct {
				Something string `json:"something"`
			} `json:"arguments"`
		} `json:"sources"`
	} `json:"destinations"`
}

What I ideally would prefer it would generate is:

type AutoGenerated struct {
	Destinations []struct {
		Username string `json:"username"`
		Avatar string `json:"avatar"`
		Webhook string `json:"webhook"`
		Cron string `json:"cron"`
		Sources []struct {
			Service string `json:"service"`
			Chance int `json:"chance"`
			Arguments json.RawMessage `json:"arguments"`
		} `json:"sources"`
	} `json:"destinations"`
}

Because it would see that same structure nodes contain differing data and a uniform structure can't be constructed hence it should be handled downstream (via json.RawMessage).

JSON to go is not working when json list has "null" values

Program

https://play.golang.org/p/RCIvR0wGjvZ

package main

import (
	"fmt"
	"encoding/json"
)

// genereated using https://mholt.github.io/json-to-go/
type DebeziumSchema struct {
	Type        string   `json:"type"`
	Name        string   `json:"name"`
	Namespace   string   `json:"namespace"`
	Fields      []Fields `json:"fields"`
	ConnectName string   `json:"connect.name"`
}
type Fields struct {
	Name    string        `json:"name"`
	Type    []interface{} `json:"type"`
	Default interface{}   `json:"default,omitempty"`
}

func main() {
	jsonStr := `{"type":"record","name":"Envelope","namespace":"datapipe.inventory.customers","fields":[{"name":"before","type":["null",{"type":"record","name":"Value","fields":[{"name":"id","type":"int"},{"name":"first_name","type":"string"},{"name":"last_name","type":"string"},{"name":"email","type":"string"}],"connect.name":"datapipe.inventory.customers.Value"}],"default":null},{"name":"after","type":["null","Value"],"default":null},{"name":"source","type":{"type":"record","name":"Source","namespace":"io.debezium.connector.mysql","fields":[{"name":"version","type":"string"},{"name":"connector","type":"string"},{"name":"name","type":"string"},{"name":"ts_ms","type":"long"},{"name":"snapshot","type":[{"type":"string","connect.version":1,"connect.parameters":{"allowed":"true,last,false"},"connect.default":"false","connect.name":"io.debezium.data.Enum"},"null"],"default":"false"},{"name":"db","type":"string"},{"name":"table","type":["null","string"],"default":null},{"name":"server_id","type":"long"},{"name":"gtid","type":["null","string"],"default":null},{"name":"file","type":"string"},{"name":"pos","type":"long"},{"name":"row","type":"int"},{"name":"thread","type":["null","long"],"default":null},{"name":"query","type":["null","string"],"default":null}],"connect.name":"io.debezium.connector.mysql.Source"}},{"name":"op","type":"string"},{"name":"ts_ms","type":["null","long"],"default":null},{"name":"transaction","type":["null",{"type":"record","name":"ConnectDefault","namespace":"io.confluent.connect.avro","fields":[{"name":"id","type":"string"},{"name":"total_order","type":"long"},{"name":"data_collection_order","type":"long"}]}],"default":null}],"connect.name":"datapipe.inventory.customers.Envelope"}
`
	var schema DebeziumSchema
	err := json.Unmarshal([]byte(jsonStr), &schema)
	if err != nil {
		panic(err)
	}
	
	fmt.Printf("%+v\n", schema)
}

Error

panic: json: cannot unmarshal object into Go struct field Fields.fields.type of type []interface {}

More Info: https://stackoverflow.com/questions/63564543/decode-a-debeuzium-event-schema-into-a-meaningful-datastructure-in-golang

Question

Please suggest why such jsons are not converting and would be right go type for this scenario?

Error on generation of nested objects in array

Found a little issue on substructures in nested objects in array.

For example :

[
  {
    "a": 1,
    "b": {
	"b1": 1,
	"b2": "B2"
    }
  },
  {
    "b": {
  	"b3": 3,
        "b4": "B4"
    }
  }
]

will generate:

type AutoGenerated []struct {
	A int `json:"a,omitempty"`
	B struct {
		B1 int    `json:"b1"`
		B2 string `json:"b2"`
	} `json:"b,omitempty"`
	B struct {
		B3 int    `json:"b3"`
		B4 string `json:"b4"`
	} `json:"b,omitempty"`
}

Bug with nested arrays

I tried to answer this question in StackOverFlow with json-to-go, but I've found a bug, this json
[[[{"abc": "a1"}]]] has to be converted as slice of slices:

type AutoGenerated [][][]struct {
    Abc string `json:"abc"`
}
// or
type AutoGenerated [][]interface{}

To be corrected Unmarshal() like here

CSV Parsing

Matt,

Last week you recommended Papa Parse for parsing CSV data structures to Go structs. I used your JSON-to-Go as a starting template and came up with:

https://alexmullins.github.io/csv-to-go/

Papa Parse made the task extremely simple. Just parse the CSV and set the scope to the .data JSON object representing the CSV data and that's it. Couldn't have been easier!

The only quirk I've found is the need to use "Shift+enter" to get the '\n' for parsing.

I'll come up with a few sample data structures to parse and add them later.

Go to JSON

I was using the site to convert JSON to Go structs, but recently I wanted to do an opposite to get a JSON string from my Go struct, and it's not yet possible.

Do you think it will make sense to have this option as well? Using left/right arrows and make interface bi-directional.

If you are happy with this idea, I can provide a PR.

About escape characters

I tried json-to-go with the chrome-lighthouse json file. But struct names are not cleared, so I can't use them. Therefore I can't unmarshall json.

Example:

 "lighthouse-core/audits/is-on-https.js | title": [
        "audits[is-on-https].title"
      ],

result:

LighthouseCoreAuditsIsOnHTTPSJsTitle            []string `json:"lighthouse-core/audits/is-on-https.js 
| title"`

array field parse error

like this:

[
  {
    "a": 1
  },
  {
    "a": "1"
  }
]

parse ret:

type AutoGenerated []struct {
	A int `json:"a"`
}

"A" should be interface{}, not "int".

non-anonymous struct regression

The following json works for previous anonymous struct, but not the current non-anonymous structs. I just get undefined.

Would you double-check please? Thx!

{
  "id": "7a305b33-471c-42cf-9baf-f5220dc17180",
  "version": "1.1",
  "name": "Dummy",
  "url": "",
  "tests": [{
    "id": "3cd0b9fa-aba7-4f9a-b278-c5b43fd9b6be",
    "name": "SeleniumIDE",
    "commands": [{
      "id": "39b58390-385c-4a1e-8915-a993f08cc165",
      "comment": "",
      "command": "open",
      "target": "https://www.seleniumhq.org/",
      "targets": [],
      "value": ""
    }, {
      "id": "6458c851-6c8b-4b82-81d6-66eede61fa2f",
      "comment": "Goto \"Projects\"",
      "command": "echo",
      "target": "",
      "targets": [],
      "value": "Test Step 1"
    }, {
      "id": "bf6c20ea-1a4a-4235-969e-d2b04d193a5b",
      "comment": "",
      "command": "click",
      "target": "linkText=Projects",
      "targets": [
        ["linkText=Projects", "linkText"],
        ["css=a[title=\"Selenium Projects\"]", "css"],
        ["css=#menu_projects > a", "css:finder"],
        ["xpath=//a[contains(text(),'Projects')]", "xpath:link"],
        ["xpath=//li[@id='menu_projects']/a", "xpath:idRelative"],
        ["xpath=//a[contains(@href, '/projects/')]", "xpath:href"],
        ["xpath=//li[5]/a", "xpath:position"]
      ],
      "value": ""
    }, {
      "id": "b4e645f8-c16d-45a6-8116-c36b90ad3a68",
      "comment": "Goto \"Selenium IDE\"",
      "command": "echo",
      "target": "",
      "targets": [],
      "value": "Test Step 2"
    }, {
      "id": "ec99567d-e01b-46f8-b773-9a963ef9cc67",
      "comment": "Get into https://www.seleniumhq.org/selenium-ide/",
      "command": "click",
      "target": "linkText=Selenium IDE",
      "targets": [
        ["linkText=Selenium IDE", "linkText"],
        ["css=h3:nth-child(9) > a", "css:finder"],
        ["xpath=//a[contains(text(),'Selenium IDE')]", "xpath:link"],
        ["xpath=//div[@id='mainContent']/div/h3[3]/a", "xpath:idRelative"],
        ["xpath=//a[contains(@href, '/selenium-ide/')]", "xpath:href"],
        ["xpath=//h3[3]/a", "xpath:position"]
      ],
      "value": ""
    }, {
      "id": "d5886005-7d6d-4cbf-b400-1feaebb51546",
      "comment": "Goto \"Doc\"",
      "command": "echo",
      "target": "",
      "targets": [],
      "value": "Test Step 3"
    }, {
      "id": "18dc810f-2753-471c-b304-5ded76b99d60",
      "comment": "Get into https://www.seleniumhq.org/selenium-ide/docs/en/introduction/getting-started/",
      "command": "click",
      "target": "linkText=Docs",
      "targets": [
        ["linkText=Docs", "linkText"],
        ["css=li > a", "css"],
        ["css=li:nth-child(1) > a", "css:finder"],
        ["xpath=//a[contains(text(),'Docs')]", "xpath:link"],
        ["xpath=//a[contains(@href, '/selenium-ide/docs/en/introduction/getting-started')]", "xpath:href"],
        ["xpath=//li/a", "xpath:position"]
      ],
      "value": ""
    }]
  }],
  "suites": [{
    "id": "ef0df0fa-eb97-4d88-9e8c-b3aa0be8a687",
    "name": "Default Suite",
    "persistSession": false,
    "parallel": false,
    "timeout": 300,
    "tests": ["3cd0b9fa-aba7-4f9a-b278-c5b43fd9b6be"]
  }],
  "urls": [],
  "plugins": []
}

Originally posted by @suntong in #35 (comment)

Copy struct to clipboard

Hey @mholt! Thank you so much for this tool, the amount of time you've saved me is astounding.

To make things even easier, would you be open to me adding a "copy to clipboard" on the output field? I think it'd be quite nice :)

struct body parse miss

for example:
{
"mounts": [
{
"child": {
"path": "blocks",
"shardFunc": "/repo/flatfs/shard/v1/next-to-last/2",
"sync": true,
"type": "flatfs"
},
"mountpoint": "/blocks",
"prefix": "flatfs.datastore",
"type": "measure"
},
{
"child": {
"compression": "none",
"path": "datastore",
"type": "levelds"
},
"mountpoint": "/",
"prefix": "leveldb.datastore",
"type": "measure"
}
],
"type": "mount"
}

parsed struct:
type AutoGenerated struct {
Mounts []struct {
Child struct {
Path json:"path"
ShardFunc json:"shardFunc"
Sync json:"sync"
Type json:"type"
} json:"child"
Mountpoint json:"mountpoint"
Prefix json:"prefix"
Type json:"type"
} json:"mounts"
Type string json:"type"
}

the second child's element compression was missed

Request for Go Package

It would have been amazing if we had a JSON-TO-GO package which converts our unexpected JSON to definitive Go structure.

Objects of varying structure within a list not added to struct

The input string:

{
    "native": {
        "ver": 1,
        "link": {
            "url": "deeplink://deeplink/url/into/app",
            "fallback": "http: //i.am.a/URL",
            "clicktrackers": [
                "http: //a.com/a",
                "http: //b.com/b"
            ]
        },
        "imptrackers": [
            "http: //a.com/a",
            "http: //b.com/b"
        ],
        "assets": [
            {
                "id": 1,
                "title": {
                    "text": "InstallBOA"
                },
                "link": {
                    "url": "http: //i.am.a/URL"
                }
            },
            {
                "id": 2,
                "data": {
                    "value": 5
                }
            },
            {
                "id": 3,
                "img": {
                    "url": "http: //cdn.mobad.com/ad.png",
                    "w": 64,
                    "h": 64
                }
            },
            {
                "id": 4,
                "data": {
                    "value": "Install"
                },
                "link": {
                    "url": "http: //i.am.a/URL"
                }
            }
        ]
    }
}

returns the Go Struct :

type Autogenerated struct {

    Native struct {

        Ver int `json:"ver"`

        Link struct {

            URL string `json:"url"`

            Fallback string `json:"fallback"`

            Clicktrackers []string `json:"clicktrackers"`

        } `json:"link"`

        Imptrackers []string `json:"imptrackers"`

        Assets []struct {

            ID int `json:"id"`

            Title struct {

                Text string `json:"text"`

            } `json:"title"`

            Link struct {

                URL string `json:"url"`

            } `json:"link"`

        } `json:"assets"`

    } `json:"native"`

}

the "img" object is missing from the assets struct. i appreciate that this JSON is kinda ugly, but still a bug!

Map interface version

Hello @mholt,
I construct a similar version of this tool: https://github.com/rodrigo-brito/json-to-go-map
That version converts the JSON to a map[string]interface{}, that can be used for simple serialization in tests or small features.

Your tool is very useful and amazing, helped me a lot, so many times. Thank you so much! ❤️
I hope that you enjoy this version.

Best regards,
Rodrigo Brito

Option to generate non-anonymous structs as output

I have found this application extremely useful. Thank you for your time and effort!

However, to enable the re-use of the nested structures ( not just for parsing ) , It would be great to have an option to generate named structs.
Instead of this

type ConfigurationData struct {
	ApplicationDisplay struct {
		Title          string `json:"title"`
		Subtitle       string `json:"subtitle"`
		WelcomeMessage string `json:"welcomeMessage"`
	} `json:"applicationDisplay"`
}

it would generate

type ApplicationDisplay struct {
    Title          string `json:"title"`
    Subtitle       string `json:"subtitle"`
    WelcomeMessage string `json:"welcomeMessage"`
}

type ConfigurationData struct {
    ApplicationDisplay ApplicationDisplay `json:"applicationDisplay"`
}

Error while parsing valid json

First of all, thank you for this tool it is very helpful.

I was trying to encode this value:

[{"holder1": {"type1": [["value1", "value2"], ["value1", "value2"]]}}]

And it resulted in this error:

5:15: expected ';', found '[' (and 1 more errors)

The smallest structure that still shows the error is the following.

[{"holder1": {"type1": [["value"]]}}]

not support uint64

uint64 value as 17307661572205707265 will be convert to int64, which case unmarshal error

Missing data types in nested struct

Take the JSON object below and try to generate a Go struct.

You’ll notice that both “user_agent” and “referer” will end up lacking the “string” type.

{
  "project": "90368",
  "logger": "javascript",
  "platform": "javascript",
  "request": {
    "user_agent": "Foobar",
    "referer": "https://cixtor.com/"
  },
  "release": "v3-1633-gbb54e4ad",
  "event_id": "b0cfac40a3374cc686b1"
}

missingtype

Problem with array of structs

I love this tool and love the recent upgrade to split out the different struct types!

I ran into a possible bug with arrays of structs, though. I want to fix it but I'm not sure how and could use some pointers.

I tried this minimal JSON where array contains an array of a struct {"word":"X"}:

 {
 	"array": [{
 		"word": "hello"
 	}, {
 		"word": "world"
 	}]
 }

which will give me the following Inline definition:

type AutoGenerated struct {
	Array []struct {
		Word `json:"word"`
	} `json:"array"`
}
  1. There is a problem that this is not a valid inline since the Word doesn't have a type (it should be string).
  2. When I uncheck inline it will just give a different error: 2:11: expected type, found 'STRING'

I haven't seen this problem anywhere else, except when I have the array of structs.

Thanks!

This was and has been a HUGE timesaver. Thank you so much!

Merge duplicate struct definitions

Where there are multiple properties which reuse the same nested properties, the corresponding struct definition should be flattened. Take the following JSON:

{
   "filter":{
      "sitereference":[
         {
            "value":"shshs"
         }
      ],
      "transactionreference":[
         {
            "value":"3-64-25205"
         }
      ]
   }
}

Expected output:

type AutoGenerated struct {
	Filter Filter `json:"filter"`
}

type FilterAutoGenerated struct {
	Value string `json:"value"`
}

type Filter struct {
	Sitereference        []FilterAutoGenerated `json:"sitereference"`
	Transactionreference []FilterAutoGenerated `json:"transactionreference"`
}

Actual output:

type AutoGenerated struct {
	Filter Filter `json:"filter"`
}

type Sitereference struct {
	Value string `json:"value"`
}

type Transactionreference struct {
	Value string `json:"value"`
}

type Filter struct {
	Sitereference        []Sitereference        `json:"sitereference"`
	Transactionreference []Transactionreference `json:"transactionreference"`
}

Name like PM1.0 gets "translated" into PM1.1.

Hi. Thanks for the tool, this is a great thing to avoid typos and reduce efforts.
I found an issue when using it, here the example:

JSON:

{
	"ts": 1554294203,
	"tem": 19.30,
	"hum": 47.70,
	"PM1.0": 0,
	"PM2.5": 0,
	"PM10.": 0,
	"P0.3": 48,
	"P0.5": 16,
	"P1.0": 2,
	"P2.5": 0,
	"P5.0": 0,
	"P10.": 0
}

Produces:

type AutoGenerated struct {
	Ts   int     `json:"ts"`
	Tem  float64 `json:"tem"`
	Hum  float64 `json:"hum"`
	PM11 int     `json:"PM1.1"`
	PM25 int     `json:"PM2.5"`
	PM10 int     `json:"PM10."`
	P03  int     `json:"P0.3"`
	P05  int     `json:"P0.5"`
	P11  int     `json:"P1.1"`
	P25  int     `json:"P2.5"`
	P51  int     `json:"P5.1"`
	P10  int     `json:"P10."`
}

Where as you can see the PM1.0 , P1.0 and P5.0 get a wrong name

Regards,

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.