Golang : Process json data with Jason package
While writing out the tutorial on how to read json data and save to csv, I was thinking ... somehow there must be a third party package out there that will make life easier.
Today, I found the package at https://github.com/antonholmquist/jason. The code below demonstrate how to use Jason package to create an object named Person
easily for further manipulation.
package main
import (
"bufio"
"fmt"
"github.com/antonholmquist/jason"
"os"
)
func main() {
// read data from file
jsonDataFromFile, err := os.Open("./data.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer jsonDataFromFile.Close()
reader := bufio.NewReader(jsonDataFromFile)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
person, _ := jason.NewObjectFromBytes([]byte(scanner.Text()))
name, _ := person.GetString("Name") //case sensitive
age, _ := person.GetNumber("Age")
job, _ := person.GetString("Job")
fmt.Printf(" %s, %v job is %s\n", name, age, job)
}
}
Output :
Adam, 36 job is CEO
Eve, 34 job is CFO
Mike, 38 job is COO
Input from data.json file
{"Name":"Adam","Age":36,"Job":"CEO"},
{"Name":"Eve","Age":34,"Job":"CFO"},
{"Name":"Mike","Age":38,"Job":"COO"}
Please see other functions to manipulate json data at https://github.com/antonholmquist/jason
References :
https://godoc.org/github.com/antonholmquist/jason
https://www.socketloop.com/tutorials/golang-read-a-file-line-by-line
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.4k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+15.8k Golang : Get sub string example
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+5.2k Golang : Get S3 or CloudFront object or file information
+15.7k Golang : Read a file line by line
+8.3k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+6.3k Grep : How to grep for strings inside binary data
+21.9k Golang : Repeat a character by multiple of x factor
+7.4k Javascript : Push notifications to browser with Push.js
+12.3k Golang : HTTP response JSON encoded data
+36.1k Golang : Convert(cast) int64 to string
+11.5k Golang : GTK Input dialog box examples