Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Storing Data in JSON
3.
Encoding and Decoding Data
4.
Encoding Data
5.
Decoding Data
6.
Unstructured Data
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Basic of Json with Golang

Author APURV RATHORE
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

JavaScript Object Notation (JSON) is a widely used data format built from JavaScript's object literals as defined by the ECMAScript computer language standard. It is an introductory textual format that uses UTF-8 encoding and is primarily used for data storage and transmission. The self-descriptive nature of data representation improves readability and is frequently used as a data exchange intermediate in web programming and client-server communication.

The article will demonstrate how to work with JSON files using Go's standard library.

For decoding and encoding, the data types are:

  • bool representing JSON boolean
  • float64 representing JSON numbers
  • string representing JSON strings
  • nil representing JSON null
  • array representing JSON array
  • map representing JSON object
  • struct representing JSON object

Storing Data in JSON

Strings, integers, Booleans, and null are the four primitive kinds that JSON can represent. Structured types, such as objects and arrays, can also be represented using it. In JSON, a string is a series of 0 or more Unicode characters, whereas an object is an unordered collection of 0 or more named/value pairs. The name of the name/value pair is a string, while the value can be any primitive or structured type, including string, integer, Boolean, null, object, or array. A series of zero or more values are represented by an array.

Data in JSON is represented using key-value pairs separated by commas, and curly braces are used to enclose the objects. 

Example:

{
    "roll_no": 12,
    "name" : "Apurv",
    "subjects": {
        "core": ["calculus","DSA","DBMS"],
        "non-core": ["economics","marketing","existentialism"]
    }
}

 

The above shows an example of a JSON object. It contains key/value pairs such as (“roll_no”,12) and ("name" : "Apurv"). It also contains another object named “subjects,” which also has its key/value pairs. In this fashion, an object might have several nested inner objects that are all represented in the same way.

The inner object contains a key “core,” which has value represented by an array of values enclosed by square brackets. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Encoding and Decoding Data

It's worth noting that the JSON data format can be readily converted to a struct type in Go. When we encode and decode JSON to and from the struct, the key of the JSON object becomes the struct field name. This is the normal practice; however, we may always use an explicit JSON tag to represent the key, as shown below:

 

type Student struct {
    Roll        int         `json:"Roll"`
    Name        string      `json:"StudentName"`
    School      string      `json:"School"`
}

Encoding Data

Syntax:

Syntax: func Marshal(v interface{}) ([]byte, error)

 

The encoding/json package's json.Marshal method provides the essential functionality for encoding a struct type to JSON data. The function returns a byte representation of the encoded JSON value after encoding. The conversion of a struct type to JSON data is straightforward. 

Example:

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Roll   int    `json:"Roll"`
    Name   string `json:"StudentName"`
    School string `json:"School"`
}

func main() {

    studentOne := Student{}

    studentOne.Name = "Apurv"
    studentOne.Roll = 12
    studentOne.School = "Stanford"

    studentEncoded, _ := json.Marshal(studentOne)

    // studentEncoded is in byte format, hence to print it, we must need to convert it into string
    fmt.Println(string(studentEncoded))
}

 

Output:

{"Roll":12,"StudentName":"Apurv","School":"Stanford"}

Decoding Data

Syntax:

Syntax: func Unmarshal(data []byte, v interface{}) error

The encoding/json package's json.Marshal method provides the essential functionality for decoding JSON data to a struct type

Example: 

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Roll   int    
    Name   string
    School string
}

func main() {

    var student Student
    jsonData := []byte (`{
        "Roll":12,
        "School": "Stanford",
        "Name":"Apurv"
        }`)
    err := json.Unmarshal(jsonData, &student)
    if err != nil {
        fmt.Println(err)
    }        
    fmt.Println("The decoded struct is:", student)
}

 

Output:

The decoded struct is: {12 Apurv Stanford}

Unstructured Data

Syntax:

var reading map[string]interface{}
err := json.Unmarshal([]byte(stringFormat), &reading)

 

Sometimes it may be the case when you have the JSON as a string, but you don’t understand the structure of it. Hence you aren’t able to build a pre-defined struct into which you can unmarshal your JSON.

In this case, you can use an alternative approach in which you can use `map[string]interface{}` to marshall into. 

Example:

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Roll   int    
    Name   string
    School string
}

func main() {
    stringFormat:= `{
        "Roll":12,
        "School": "Stanford",
        "Name":"Apurv"
        }`

    var reading map[string]interface{}
    err := json.Unmarshal([]byte(stringFormat), &reading)
    if (err!=nil){
        fmt.Printf("Error")
    }
    fmt.Printf("%+v\n", reading)

}

 

Output:

map[Name:Apurv Roll:12 School:Stanford]

FAQs

  1. What is JSON?
    JSON is an open standard file format and data exchange format that stores and transmits data objects made up of key-value pairs and arrays using human-readable language. It's a popular data format with a wide range of applications in electronic data interchange, including online applications that communicate with servers.
     
  2. How is data represented in JSON?
    Data in JSON is represented using key-value pairs separated by commas, and curly braces are used to enclose the objects. 
     
  3. Which functions are used in Golang to encode and decode JSON objects?
    The Marshal() function contained in the encoding/json package is used to encode and decode the JSON objects. 

Key Takeaways

In this article, we have extensively discussed the basics of JSON and its implementation in the Go programming language. We hope that this blog has helped you enhance your knowledge regarding JSON and if you would like to learn more, check out our articles on GoLang. Do upvote our blog to help other ninjas grow. 

Happy Coding!

 

Previous article
Golang Program to Represent a Binary Heap
Next article
Go Interface Type
Live masterclass