GoLand 2021.3 Help

Working with JSON

JavaScript Object Notation (JSON) is a textual format in which you can represent, store, and transfer structural data.

In Go, map and struct data types provide the closest JSON representation as they can store data in a key:value format.

When you paste JSON in GoLand, the IDE suggests converting it to the struct type. All the necessary struct field tags are generated and added automatically.

converting JSON to struct

You can use the copy-and-paste approach or the Generate Go Type from JSON dialog.

Generate struct fields

  1. Press Ctrl+Shift+A to invoke the Go to Action search.

  2. Search for the Generate Go Type from JSON option and run it.

  3. Paste or write your JSON in the text field.

  4. Click Generate.

    Modify JSON for a struct in a separate dialog

Intention actions

By using intention actions, you can add new tags, keys and modify the code style of tag keys.

Add new tags to a struct field

  1. Click a struct field and press Alt+Enter.

  2. Select Add key to tags.

    Add new tags to a struct field

Modify keys in field tags

  1. Click a struct field and press Alt+Enter.

  2. Select Update key value in tags.

    Add new tags to a struct field

Change code style of tag keys

  1. Click a key in tag and press Alt+Enter.

  2. Select Change field name style in tags.

    Change code style of tag keys

Code completion

When you modify tag keys, GoLand displays a list of the most popular values for these tags. For example, json suggests omitempty; xml has attr, cdata, chardata, innerxml, and others; asn1 has optional, explicit, generalized, and so on.

code-completion-json

Style for struct tags

  • When you start filling out a tag, right after you type backticks (`), GoLand will suggest entering a key. Press Tab or Enter and you will see a list of options. Choose the style of the value name. The IDE saves your choice, and it will suggest the same style first in the list for other fields of this struct.

    autocompletion for struct tags

Generate fields for an empty struct

If you have an empty struct, you can generate all the necessary fields and tags from JSON. To do that, call the Generate Go Type from JSON dialog by using the Go to Action search and paste your JSON in the text field. Alternatively, you can navigate to Code | Generate… and select Type from JSON in the popup window.

Generate fields for an empty struct
Last modified: 04 October 2021