Convert JSON To CSV In Golang with Example

Golang csv.NewWriter() is an inbuilt function that converts the data structure into csv format. CSV(Comma Separated Value) is a highly accepted data language, commonly used by Excel and spreadsheets, and as such is very useful if your script is producing data, and you want it in a standard format.

The CSV package has a NewWriter() function that returns the Writer object which is used for writing the CSV data. The csv.Writer() writes csv records that are terminated by the newline and uses the comma as a field delimiter.

See the one by one following code snippets.

Let’s create a json file. We will name it company.json.

[
  { "App": "Instagram", "Company": "Facebook", "Category": "Social Media" },
  { "App": "WeChat", "Company": "Tencent", "Category": "Social Media" },
  { "App": "Hotstar", "Company": "Disney", "Category": "Entertainment" },
  { "App": "CNBC", "Company": "Comcast", "Category": "News" },
  { "App": "SnapChat", "Company": "Snap", "Category": "Social Media" }
]

So, our JSON object has three properties.

  1. App
  2. Company
  3. Category

Now, let’s write the **hello.go **file.

First, we need to import the following go packages.

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

Package csv reads and writes the comma-separated values (CSV) files.

There are many kinds of CSV files and this package supports the format described in RFC 4180.

Package json implements the encoding and decoding of JSON as defined in RFC 7159. The mapping between the JSON and Go values is described in the docs for the Marshal and Unmarshal functions.

Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs‘ are derived from C’s but are more straightforward.

Package io/ioutil implements some I/O utility functions.

Package os provides the platform-independent interface to operating system functionality. The design is Unix-like, although an error handling is Go-like; failing calls return values of type error rather than error numbers.

Now, the next step is to define the struct.

// Application struct

type Application struct {
	App      string
	Company  string
	Category string
}

Golang Structs are the user-defined type that contains the collection of named fields/properties. It is used to group related data to form a single unit.

Now, define the main() function.

The first step is to read file using **ioutil.ReadFile() **function.

jsonDataFromFile, err := ioutil.ReadFile("./company.json")

if err != nil {
   fmt.Println(err)
}

We have already defined a **json **file—the ioutil.ReadFile() function reads the file named by filename and returns the contents.

Now, Unmarshal the contents of the json file.

var jsonData []Application
err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

if err != nil {
	fmt.Println(err)
}

Now, create a csv file in Golang using **os.Create() **function.

csvFile, err := os.Create("./data.csv")

if err != nil {
	fmt.Println(err)
}
defer csvFile.Close()

Now, see the following code.

writer := csv.NewWriter(csvFile)

for _, usance := range jsonData {
	var row []string
	row = append(row, usance.App)
	row = append(row, usance.Company)
	row = append(row, usance.Category)
	writer.Write(row)
}

// remember to flush!
writer.Flush()

In the above code snippet, we are creating the writer object and then appending one by one json content to that csv file. So, that json content will be converted into a csv file.

A two-dimensional slice row contains sample csv records. Go os.Create() function creates the csv file data.csv; truncate all it’s records if already exists and returning the instance of os.File() object.

The csvwriter.Write(row) function is called to write each slice of the strings to a file as CSV records.

Our whole final code is the following.

// hello.go

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

// Application struct
type Application struct {
	App      string
	Company  string
	Category string
}

func main() {
	// read data from file
	jsonDataFromFile, err := ioutil.ReadFile("./company.json")

	if err != nil {
		fmt.Println(err)
	}

	// Unmarshal JSON data
	var jsonData []Application
	err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

	if err != nil {
		fmt.Println(err)
	}

	csvFile, err := os.Create("./data.csv")

	if err != nil {
		fmt.Println(err)
	}
	defer csvFile.Close()

	writer := csv.NewWriter(csvFile)

	for _, usance := range jsonData {
		var row []string
		row = append(row, usance.App)
		row = append(row, usance.Company)
		row = append(row, usance.Category)
		writer.Write(row)
	}

	// remember to flush!
	writer.Flush()
}

Output

Instagram,Facebook,Social Media
WeChat,Tencent,Social Media
Hotstar,Disney,Entertainment
CNBC,Comcast,News
SnapChat,Snap,Social Media

Finally, Golang: Convert JSON to CSV File Example is over.

#json #go #golang

What is GEEK

Buddha Community

Convert JSON To CSV In Golang with Example
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

Convert JSON To CSV In Golang with Example

Golang csv.NewWriter() is an inbuilt function that converts the data structure into csv format. CSV(Comma Separated Value) is a highly accepted data language, commonly used by Excel and spreadsheets, and as such is very useful if your script is producing data, and you want it in a standard format.

The CSV package has a NewWriter() function that returns the Writer object which is used for writing the CSV data. The csv.Writer() writes csv records that are terminated by the newline and uses the comma as a field delimiter.

See the one by one following code snippets.

Let’s create a json file. We will name it company.json.

[
  { "App": "Instagram", "Company": "Facebook", "Category": "Social Media" },
  { "App": "WeChat", "Company": "Tencent", "Category": "Social Media" },
  { "App": "Hotstar", "Company": "Disney", "Category": "Entertainment" },
  { "App": "CNBC", "Company": "Comcast", "Category": "News" },
  { "App": "SnapChat", "Company": "Snap", "Category": "Social Media" }
]

So, our JSON object has three properties.

  1. App
  2. Company
  3. Category

Now, let’s write the **hello.go **file.

First, we need to import the following go packages.

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

Package csv reads and writes the comma-separated values (CSV) files.

There are many kinds of CSV files and this package supports the format described in RFC 4180.

Package json implements the encoding and decoding of JSON as defined in RFC 7159. The mapping between the JSON and Go values is described in the docs for the Marshal and Unmarshal functions.

Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs‘ are derived from C’s but are more straightforward.

Package io/ioutil implements some I/O utility functions.

Package os provides the platform-independent interface to operating system functionality. The design is Unix-like, although an error handling is Go-like; failing calls return values of type error rather than error numbers.

Now, the next step is to define the struct.

// Application struct

type Application struct {
	App      string
	Company  string
	Category string
}

Golang Structs are the user-defined type that contains the collection of named fields/properties. It is used to group related data to form a single unit.

Now, define the main() function.

The first step is to read file using **ioutil.ReadFile() **function.

jsonDataFromFile, err := ioutil.ReadFile("./company.json")

if err != nil {
   fmt.Println(err)
}

We have already defined a **json **file—the ioutil.ReadFile() function reads the file named by filename and returns the contents.

Now, Unmarshal the contents of the json file.

var jsonData []Application
err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

if err != nil {
	fmt.Println(err)
}

Now, create a csv file in Golang using **os.Create() **function.

csvFile, err := os.Create("./data.csv")

if err != nil {
	fmt.Println(err)
}
defer csvFile.Close()

Now, see the following code.

writer := csv.NewWriter(csvFile)

for _, usance := range jsonData {
	var row []string
	row = append(row, usance.App)
	row = append(row, usance.Company)
	row = append(row, usance.Category)
	writer.Write(row)
}

// remember to flush!
writer.Flush()

In the above code snippet, we are creating the writer object and then appending one by one json content to that csv file. So, that json content will be converted into a csv file.

A two-dimensional slice row contains sample csv records. Go os.Create() function creates the csv file data.csv; truncate all it’s records if already exists and returning the instance of os.File() object.

The csvwriter.Write(row) function is called to write each slice of the strings to a file as CSV records.

Our whole final code is the following.

// hello.go

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

// Application struct
type Application struct {
	App      string
	Company  string
	Category string
}

func main() {
	// read data from file
	jsonDataFromFile, err := ioutil.ReadFile("./company.json")

	if err != nil {
		fmt.Println(err)
	}

	// Unmarshal JSON data
	var jsonData []Application
	err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

	if err != nil {
		fmt.Println(err)
	}

	csvFile, err := os.Create("./data.csv")

	if err != nil {
		fmt.Println(err)
	}
	defer csvFile.Close()

	writer := csv.NewWriter(csvFile)

	for _, usance := range jsonData {
		var row []string
		row = append(row, usance.App)
		row = append(row, usance.Company)
		row = append(row, usance.Category)
		writer.Write(row)
	}

	// remember to flush!
	writer.Flush()
}

Output

Instagram,Facebook,Social Media
WeChat,Tencent,Social Media
Hotstar,Disney,Entertainment
CNBC,Comcast,News
SnapChat,Snap,Social Media

Finally, Golang: Convert JSON to CSV File Example is over.

#json #go #golang

Converting GoLang Structs to JSON

If you’re struggling with understanding how GoLang reads JSON you will need learn these tips to navigate quickly to be productive. Here are a few tips to use when working with JSON within the programming language Golang.

JSON-to-Go UnMarshal Function in Go?

Data := make(map[string]interface{})

var data = `
{
  "array": [
 1,
 2,
 3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
 "a": "b",
 "c": "d",
 "e": "f"
  },
  "string": "Hello World"
}`
if err := json.Unmarshal([]byte(data), &Data); err != nil {      panic(err)   }

You’ll be able to print this GoLang (Go) Struct using the following code below.

fmt.Printf("%s", jsonMap)

#golang #golang-tutorial #programming #json #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

Dynamic JSON in Golang | Golang Tutorial JSON | Golang Tutorial

A Simple Example to show How to Unmarshall A Dynamic JSON in GoLang.
Dynamic JSON Example in Golang
Install Package :go get github.com/Jeffail/gabs
Gabs is a small utility for dealing with dynamic or unknown JSON structures in Go. It’s pretty much just a helpful wrapper for navigating hierarchies of map[string]interface{} objects provided by the encoding/json package. It does nothing spectacular apart from being fabulous.

#golang #golangTutorial #GolangJSON #dynamicJsonGolang #GOJSON #golangSimpleExample

#golang #golangjson #go #json