Waylon  Bruen

Waylon Bruen

1619664674

The Ultimate Guide to JSON in Go

Being a language built for the web, Go offers feature-rich support for working with JSON data.  JSON (JavaScript Object Notation) is an unbelievably popular data interchange format whose syntax resembles simple JavaScript objects. It’s one of the most common ways for web applications to communicate.

Encoding and decoding with struct tags

Go takes a unique approach for working with JSON data. The best way to think about JSON data in Go is as an encoded struct. When you encode and decode a struct to JSON, the key of the JSON object will be the name of the struct field unless you give the field an explicit JSON  tag.

type User struct {
     FirstName string `json:"first_name"` // key will be "first_name"
     BirthYear int `json:"birth_year"` // key will be "birth_year"
     Email string // key will be "Email"
 }

Example marshal JSON from struct (encode)

The encoding/json package exposes a json.Marshal function that allows us to create the JSON encoding of any type, assuming that type has an encoder implemented. The good news is, all the default types have an encoder, and you’ll usually be working with structs filled with default-type fields.

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

As you can see, Marshal() takes a value as input, and returns the encoded JSON as a slice of bytes on success, or an error if something went wrong.

dat, _ := json.Marshal(User{
    FirstName: "Lane",
    BirthYear: 1990,
    Email:     "example@gmail.com",
})
fmt.Println(string(dat))

// prints:
// {"first_name":"Lane","birth_year":1990,"Email":"example@gmail.com"}

#golang #mailing-list #go

What is GEEK

Buddha Community

The Ultimate Guide to JSON in Go
Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Fannie  Zemlak

Fannie Zemlak

1599854400

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.

#go #golang #go 1.15 #go features #go improvement #go package #go new features

Christa  Stehr

Christa Stehr

1626852671

JSON with Go | How to Read JSON Files in Go

Use JSON with Go by learning to read JSON files, encode and decode structs, and define structs using tags.

Most modern applications require communication across multiple services, and JSON is one of the most popular notations for storing and transferring data across the web. In this article, we’ll explore working with JSON in Go, a popular open source language.

  • Introduction to JSON
  • Reading JSON files in Go
  • Decode JSON in Go structs
  • Encode JSON from Go structs
  • JSON tags in Go

Let’s get started!


Introduction to JSON

JSON, or JavaScript Object Notation, is a popular text format for storing, sending, and receiving information. JSON is easy to write and understand due to its simple structure that is formatted as a key-value pair using ordered lists.

JSON is language-independent, meaning it can be used with any programming language. Many languages come with built-in support for JSON.

Let’s see what the JSON format looks like with an example! In the code block below, the JSON object represents a user on a web application:

{
  "firstname": "Mohit",
  "lastname": "Khare",
  "id": "mkfeuhrer",
  "age": "24",
  "gender": "male",
  "preferred_topics": ["startups", "books", "chess", "blogging"],
  "social_links": [
    {
      "site": "twitter",
      "url": "https://twitter.com/mkfeuhrer"
    }
  ]
} 

The JSON key must be a string based on how the JSON format schema is defined. However, the value can be a string, an object, or a list of strings or objects.

Reading JSON files in Go

Save the JSON object from the code block above to a file called user.json. We’ll use ReadFile from the ioutilpackage to read the JSON file and print the data:

package main
import (
    "fmt"
    "io/ioutil"
)
func ReadJSON(filename string) ([]byte, error) {
    data, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Println("Error reading user.json", err)
        return nil, err
    }
    fmt.Println("Success reading user.json")
    return data, nil
}
func main() {
    data, err := ReadJSON("user.json")
    if err != nil {
        return
    }
    fmt.Println("Content of user.json:")
    fmt.Println(string(data))
}

The output for the code above is as follows:

Success reading user.json
Content of user.json:
{
  "firstname": "Mohit",
  "lastname": "Khare",
  "id": "mkfeuhrer",
  "age": "24",
  "gender": "male",
  "preferred_topics": [
    "startups",
    "books",
    "chess"
  ],
  "social_links": [
    {
      "site": "twitter",
      "url": "https://twitter.com/mkfeuhrer"
    }
  ]
}

Decode JSON in Go structs

Now that we can read the JSON file, we’ll parse it into Go structs. You cannot perform Go operations directly on JSON data. Instead, you must map the JSON data to the Go struct, allowing it to perform other operations.

package json in Go provides the Unmarshal function, which helps us to parse data into structs:

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

Unmarshal requires that the data be in byte array to parse it to an interface. Let’s create a struct to read the user data defined above:

// parse social link object
type SocialLink struct {
        Site string `json:"site"`
        URL  string `json:"url"`
}

// parse user object
type User struct {
        Firstname       string      `json:"firstname"`
        Lastname        string      `json:"lastname"`
        ID              string      `json:"id"`
        Age             string      `json:"age"`
        Gender          string      `json:"gender"`
        PreferredTopics []string    `json:"preferred_topics"`
        SocialLinks     []SocialLink `json:"social_links"`
}

Now, we’ll parse JSON to this struct:

func DecodeJSON(data []byte, user *User) {
    err := json.Unmarshal(data, user)
    if err != nil {
        fmt.Println("Error parsing JSON", err)
    }
    fmt.Println(*user)
}

// We call this function with the data and user Object
var user User
DecodeJSON(data, &user)

Encode JSON from Go structs

We’d also like to write JSON data from our Go application, so let’s convert the structs we created to JSON data. Go’s package json provides the Marshal function to help encode structs to JSON data:

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

Marshal requires an interface from which we’ll encode JSON data. Let’s encode our User object back to JSON:

func EncodeJSON(user *User) {
    data, err := json.Marshal(user)
    if err != nil {
        fmt.Println("Error parsing JSON", err)
    }
    fmt.Println(string(data))
}

// We call this function with the data and user Object
user := User {
    Firstname: "John",
    Lastname: "Doe",
    ID: "john",
    Age: "30",
    Gender: "male",
    SocialLinks: []SocialLink{
        {
            Site: "twitter",
            URL: "https://twitter.com/john",
        },
    },
}
EncodeJSON(data, &user)

The function above will print the JSON data:

{
  "firstname": "John",
  "lastname": "Doe",
  "id": "john",
  "age": "30",
  "gender": "male",
  "preferred_topics": null,
  "social_links": [
    {
      "site": "twitter",
      "url": "https://twitter.com/john"
    }
  ]
}

Notice carefully the preferred_topics field is null because our user object did not have a value assigned for this attribute. Now, let’s learn how we can skip empty fields.

JSON tags in Go

When we defined structs, we used a few JSON tags. Tags help us to control the key for attributes by omitting empty or null fields.

Let’s see an example of tags! In the code block below, we’ll define the Firstname attribute to use the "first name" key in JSON. We’ll omit PreferredTopics from the object if it is empty:

PreferredTopics []string `json:"preferred_topics,omitempty"`

We’ll simply ignore Age while we’re encoding/decoding JSON.

Age int `json:"-"`

We usually use omitempty when a value is optional within our structs. In our user example, we can manage if lastname of the user is not present, but we cannot add omitempty to id.

Your completed code will look like the following code block:

package main
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)
type SocialLink struct {
    Site string `json:"site"`
    URL  string `json:"url"`
}
type User struct {
    Firstname       string       `json:"firstname"`
    Lastname        string       `json:"lastname,omitempty"`
    ID              string       `json:"id"`
    Age             string       `json:"age,omitempty"`
    Gender          string       `json:"gender,omitempty"`
    PreferredTopics []string     `json:"preferred_topics,omitempty"`
    SocialLinks     []SocialLink `json:"social_links,omitempty"`
}
func ReadJSON(filename string) ([]byte, error) {
    data, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Println("Error reading user.json", err)
        return nil, err
    }
    fmt.Println("Success reading user.json")
    return data, nil
}
func DecodeJSON(data []byte, user *User) {
    err := json.Unmarshal(data, user)
    if err != nil {
        fmt.Println("Error parsing JSON", err)
    }
    fmt.Println(*user)
}
func EncodeJSON(user *User) {
    data, err := json.Marshal(user)
    if err != nil {
        fmt.Println("Error parsing JSON", err)
    }
    fmt.Println(string(data))
}
func main() {
    data, err := ReadJSON("user.json")
    if err != nil {
        return
    }
    fmt.Println("Content of user.json:")
    fmt.Println(string(data))
    var user User
    fmt.Println("\nDecode JSON data to user struct:")
    DecodeJSON(data, &user)
    // define new user
    user2 := User{
        Firstname: "John",
        Lastname:  "Doe",
        ID:        "john",
        Age:       "30",
        Gender:    "male",
        SocialLinks: []SocialLink{
            {
                Site: "twitter",
                URL:  "https://twitter.com/john",
            },
        },
    }
    fmt.Println("\nEncode struct to JSON:")
    EncodeJSON(&user2)
}  

Conclusion

In this tutorial, we learned how to read JSON files, encode and decode data to structs using the marshal and unmarshal functions, and define structs using tags.

Our example included simple fields for inputting a user’s profile information, but you can use the information from this tutorial to build a number of complex applications.

I hope you enjoyed the article and learned something useful!

Original article source at https://blog.logrocket.com

#json #go #golang

Encoding JSON from GO | JSON in GO | Golang Tutorial

Encoding structured data:
JSON in GO Programming. Simple Go program using JSON.
Golang Tutorial video.

JSON (JavaScript Object Notation) is a simple data interchange format. Syntactically it resembles the objects and lists of JavaScript. It is most commonly used for communication between web back-ends and JavaScript programs running in the browser, but it is used in many other places, too
#json #jsongolang #golang #golangprogramming #goprogram

#json #jsongolang #golang #go

Autumn  Blick

Autumn Blick

1593251880

JSON Parsing in Android - Step by Step Implementation

JSON Structures in Android

JSON uses two types of brackets that are as follows:

  • [] – To declare the elements of Array in JSON, they’re written in square brackets.
  • {} – To create JSON objects, the elements are written in curly brackets.

JSON has the following types of structures that are:

1. JSON Objects

The elements inside the curly brackets are known as Objects.

2. JSON Array

A list of values, known as Arrays.

3. JSON Key-Value

This data is stored as a pair of keys and values. Here the keys can be a name, a number for which the values can be Seema, 98767586 etc.

Why JSON Parsing in Android over XML?

Let us see some reasons for why to choose JSON over XML:

  • It is much easier and quicker with high performance
  • It can use arrays
  • Its libraries do not depend on other libraries
  • The codes written in JSON are short, clean and easy to understand
  • It is free to open use and open-source tool
  • In JSON value retrieval is easy
  • It has a fully automated way of serializing/deserializing JavaScript.
  • It is supported by many Ajax toolkits and most of the backend technologies.

Examples of XML and JSON

Let us see the code difference of JSON and XML files:

XML Example:

<?xml version= “1.0” encoding= “” ?>
<student>
        <student>
  <name> Sia Sharma</name>
  <city> Chandigarh</city>
         </student>
        <student>
  <name>Dimple D’souza</name>
  <city> Nagpur</city>
         </student>
      <student>
  <name>Anna Jones</name>
  <city> Mumbai</city>
         </student>
  </student>

JSON Example:

{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}

I hope the difference is all clear in front of you. This is how simple JSON is and how easily it could be understood.

#android tutorials #json parsing in android #json parsing in android example #json parsing in android step by step #json parsing with android #read json file android