Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
Last Updated : 23 Mar, 2023
Summarize
Comments
Improve
Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.
Syntax: func Unmarshal(data []byte, v interface{}) error
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. Example 1:
Go
// Golang program to illustrate the
// concept of parsing json to struct
package
main
import
(
"encoding/json"
"fmt"
)
// declaring a struct
type Country
struct
{
// defining struct variables
Name
string
Capital
string
Continent
string
}
// main function
func
main() {
// defining a struct instance
var
country1 Country
// data in JSON format which
// is to be decoded
Data := []
byte
(`{
"Name": "India",
"Capital": "New Delhi",
"Continent": "Asia"
}`)
// decoding country1 struct
// from json format
err := json.Unmarshal(Data, &country1)
if
err != nil {
// if error is not nil
// print error
fmt.Println(err)
}
// printing details of
// decoded data
fmt.Println("Struct is:", country1)
fmt.Printf("%s's capital is %s and it is in %s.\n", country1.Name,
country1.Capital, country1.Continent)
}
Output:
Struct is: {India New Delhi Asia}India's capital is New Delhi and it is in Asia.
Example 2:
Go
// Golang program to illustrate the
// concept of parsing JSON to an array
package
main
import
(
"encoding/json"
"fmt"
)
// declaring a struct
type Country
struct
{
// defining struct variables
Name
string
Capital
string
Continent
string
}
// main function
func
main() {
// defining a struct instance
var
country []Country
// JSON array to be decoded
// to an array in golang
Data := []
byte
(`
[
{"Name": "Japan", "Capital": "Tokyo", "Continent": "Asia"},
{"Name": "Germany", "Capital": "Berlin", "Continent": "Europe"},
{"Name": "Greece", "Capital": "Athens", "Continent": "Europe"},
{"Name": "Israel", "Capital": "Jerusalem", "Continent": "Asia"}
]`)
// decoding JSON array to
// the country array
err := json.Unmarshal(Data, &country)
if
err != nil {
// if error is not nil
// print error
fmt.Println(err)
}
// printing decoded array
// values one by one
for
i :=
range
country {
fmt.Println(country[i].Name + " - " + country[i].Capital +
" - " + country[i].Continent)
}
}
Output:
Japan - Tokyo - AsiaGermany - Berlin - EuropeGreece - Athens - EuropeIsrael - Jerusalem - Asia
Parse JSON to map
In some cases, we do not know the structure of the JSON beforehand, so we cannot define structs to unmarshal the data. To deal with cases like this we can create a map[string]interface{}
Example 1:
Go
//program to illustrate the concept of parsing JSON to map
package
main
import
(
"encoding/json"
"fmt"
)
func
main() {
//declaring a map
//key of type string and value as type interface{} to store values of any type
var
person
map
[
string
]
interface
{}
//json data to be decoded
jsonData := `{
"name"
:
"Jake"
,
"country"
:
"US"
,
"state"
:
"Connecticut"
}`
//decoding the json data and storing in the person map
err := json.Unmarshal([]
byte
(jsonData), &person)
//Checks whether the error is nil or not
if
err != nil {
//Prints the error if not nil
fmt.Println(
"Error while decoding the data"
, err.Error())
}
//printing the details of decoded data
fmt.Println(
"The name of the person is"
, person[
"name"
],
"and he lives in"
, person[
"country"
])
}
Output:
The name of the person is Jake and he lives in US
Example 2:
Go
// Golang program to illustrate the
// concept of parsing JSON to an array
package
main
import
(
"encoding/json"
"fmt"
)
func
main() {
//defining the array of persons
var
persons []
map
[
string
]
interface
{}
//json array to be decoded to an array in golang
jsonData := `[{
"name"
:
"Jake"
,
"country"
:
"US"
,
"state"
:
"Connecticut"
},
{
"name"
:
"Jacob"
,
"country"
:
"US"
,
"state"
:
"NewYork"
},
{
"name"
:
"James"
,
"country"
:
"US"
,
"state"
:
"WashingtonDC"
}
]`
//decoding JSON array to persons array
err := json.Unmarshal([]
byte
(jsonData), &persons)
if
err != nil {
fmt.Println(
"Error while decoding the data"
, err.Error())
}
//printing decoded array values one by one
for
index, person :=
range
persons {
fmt.Println(
"Person:"
, index+
1
,
"Name:"
, person[
"name"
],
"Country:"
, person[
"country"
],
"State:"
, person[
"state"
])
}
}
Output:
Person: 1 Name: Jake Country: US State: ConnecticutPerson: 2 Name: Jacob Country: US State: NewYorkPerson: 3 Name: James Country: US State: WashingtonDC
Please Login to comment...
Similar Reads
time.Parse() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Parse() function in Go language is used to parse a formatted string and then finds the time value that it forms. Moreover, this function is defined under the time package. Here, you need to import "time" package in order to use these functions. Syntax:
2 min read
Basics of JSON with GoLang
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool for JSON booleansfloat64 for JSON numbersstring f
3 min read
How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
Golang program that uses fallthrough keyword
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don't put the fallthrough in the last statement of switch ca
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
How to check equality of slices of bytes in Golang?
In Go language slice is more powerful, flexible, and convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different types of elements in the same slice. In the Go slice of byes, you are allowed to check the equality of the slices w
3 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
How to convert a slice of bytes in lowercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the lowercase usin
2 min read
io.PipeWriter.CloseWithError() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The PipeWriter.CloseWithError() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any
3 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to
9 min read
time.Round() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration 'd' to the closest multiple of 'm' duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under th
2 min read
How to add a method to struct type in Golang?
Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type. A normal function returning an integer and taking no parameter would look like. func
3 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
Check if the given slice is sorted in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can check the given slice is sorted or not with the help of Sl
3 min read
How to compare times in Golang?
With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison. Functions Used: These functions compares the times as seconds. Before(temp) - This function is used to check if the given time is before the temporary time vari
2 min read
reflect.AppendSlice() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program. Synta
2 min read
How to Deploy a Golang WebApp to Heroku?
Go, also known as "Golang," is gaining popularity among DevOps professionals in recent years. There are many tools written in Go, including Docker and Kubernetes, but they can also be used for web applications and APIs. While Golang can perform as fast as a compiled language, coding in it feels more like interpreting with standard tools such as a c
5 min read
reflect.ChanOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ChanOf() Function in Golang is used to get the channel type with the given direction and element type, i.e., t represents int, ChanOf(RecvDir, t) represents <-c
1 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name strin
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
time.Time.Year() Function in Golang with Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified "t" happens. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (t Tim
2 min read
Searching an element of float64 type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search an element of float64 type in the given slice of f
3 min read
reflect.DeepEqual() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.DeepEqual() Function in Golang is used to check whether x and y are “deeply equal” or not. To access this function, one needs to imports the reflect package in the
2 min read
reflect.Indirect() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirec
2 min read
Bitwise NOT operator in Golang
Bitwise NOT operator in the programming world usually takes one number and returns the inverted bits of that number as shown below: Bitwise NOT of 1 = 0 Bitwise NOT of 0 = 1 Example: Input : X = 010101 Output : Bitwise NOT of X = 101010 But Golang doesn't have any specified unary Bitwise NOT(~) or you can say Bitwise Complement operator like other
2 min read
Article Tags :
Trending in News
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });
Continue without supporting 😢