This question already has answers here:
json.Unmarshal returning blank structure
(1 answer)
Making HTTP responses with JSON [duplicate]
(2 answers)
Closed 3 years ago.
I'm trying to parse a json file using GoLang but it seems like not work. Am I doing right?
this is my Go Code:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type info struct {
username string `json:"username"`
password string `json:"password"`
timedelay int `json:"timedelay"`
courselist []string `json:"courselist"`
}
func main() {
var jsonParse info
file, err := ioutil.ReadFile("info.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("My file content is:\n", string(file))
fmt.Println("---------------Parsing Json File----------------")
json.Unmarshal(file, &jsonParse)
fmt.Println("My Json Parse is:\n", jsonParse)
}
and this is my json file
{
"username" : "17020726",
"password": "Blueflower",
"timedelay": 200,
"courselist": ["54"]
}
this is result of my code
My file content is:
{
"username" : "17020726",
"password": "Blueflower",
"timedelay": 200,
"courselist": ["54"]
}
---------------Parsing Json File----------------
My Json Parse is:
{ 0 []}
The info struct fields are private. Capitalize the first letters.
Related
This question already has answers here:
Parsing multiple JSON objects in Go
(4 answers)
Closed 2 years ago.
I have a json file (file.json) with following content:
file.json:
{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}
The contents of the file are exactly as above (not valid json file)
I want use data in my code but I can not Unmarshal This
What you have is not a single JSON object but a series of (unrelated) JSON objects. You can't use json.Unmarshal() to unmarshal something that contains multiple (independent) JSON values.
Use json.Decoder to decode multiple JSON values (objects) from a source one-by-one.
For example:
func main() {
f := strings.NewReader(file)
dec := json.NewDecoder(f)
for {
var job struct {
Job string `json:"job"`
}
if err := dec.Decode(&job); err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Printf("Decoded: %+v\n", job)
}
}
const file = `{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`
Which outputs (try it on the Go Playground):
Decoded: {Job:developer}
Decoded: {Job:taxi driver}
Decoded: {Job:police}
This solution works even if your JSON objects take up multiple lines in the source file, or if there are multiple JSON objects in the same line.
See related: I was getting output of exec.Command output in the following manner. from that output I want to get data which I needed
You can read string line by line and unmarshal it:
package main
import (
"bufio"
"encoding/json"
"fmt"
"strings"
)
type j struct {
Job string `json:"job"`
}
func main() {
payload := strings.NewReader(`{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`)
fscanner := bufio.NewScanner(payload)
for fscanner.Scan() {
var job j
err := json.Unmarshal(fscanner.Bytes(), &job)
if err != nil {
fmt.Printf("%s", err)
continue
}
fmt.Printf("JOB %+v\n", job)
}
}
Output:
JOB {Job:developer}
JOB {Job:taxi driver}
JOB {Job:police}
Example
This question already has answers here:
JSON and dealing with unexported fields
(2 answers)
Closed 4 years ago.
Can some one please explain to me why this code fail to decode json properly:
package main
import (
"fmt"
"os"
"log"
"encoding/json"
)
type Config struct {
mongoConnectionString string `json:"database"`
Elastic struct{
main string `json:"main"`
log string `json:"log"`
} `json:"elastic"`
logFilePath string `json:"logfile"`
}
func main(){
loadConfiguration("./config.json")
}
func loadConfiguration(file string){
var configuration Config
configFile, err := os.Open(file); if err != nil {
log.Panic("Could not open", file)
}
defer configFile.Close()
if err := json.NewDecoder(configFile).Decode(&configuration); err != nil {
log.Panic("./config.json is currupted")
}
fmt.Print(configuration.logFilePath)
}
Json data:
{
"database": "localhost",
"elastic": {
"main": "test",
"log": "test"
},
"logfile": "./logs/log.log"
}
The execution of this program will result in empty configuration.logFilePath
What am i missing?
Thanks
For the json package to properly decode from json in go, fields must be exported (capitalized) within the struct definition.
Changing Config to:
type Config struct {
MongoConnectionString string `json:"database"`
Elastic struct{
Main string `json:"main"`
Log string `json:"log"`
} `json:"elastic"`
LogFilePath string `json:"logfile"`
}
will make all fields deserialize correctly.
This question already has answers here:
How to parse/deserialize dynamic JSON
(4 answers)
Closed 3 years ago.
I have a JSON object, something like this:
{
"randomstring": {
"everything": "here",
"is": "known"
}
}
Basically everything inside the randomstring object is known, I can model that, but the randomstring itself is random. I know what it's going to be, but it's different every time. Basically all the data I need is in the randomstring object. How could I parse this kind of JSON to get the data?
Use a map where the key type is string and the value type is a struct with the fields you want, like in this example on the Playground and below:
package main
import (
"encoding/json"
"fmt"
"log"
)
type Item struct{ X int }
var x = []byte(`{
"zbqnx": {"x": 3}
}`)
func main() {
m := map[string]Item{}
err := json.Unmarshal(x, &m)
if err != nil {
log.Fatal(err)
}
fmt.Println(m)
}
This question already has an answer here:
Printing Empty Json as a result [duplicate]
(1 answer)
Closed 6 years ago.
I am trying to learn Go. I am writing a simple program to get values from JSON file in GoLang.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type bands struct {
id string `json:"id"`
name string `json:"name"`
location string `json:"location"`
year string `json:"year"`
}
func main() {
bands := getBands()
fmt.Println(bands)
}
func getBands() []bands {
raw, err := ioutil.ReadFile("../data/bands.json")
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var c []bands
json.Unmarshal(raw, &c)
return c
}
Also, below is my JSON File:
[{"id":"1","name": "The Beatles","location": "NY","year": "2012"},
{"id":"2","name": "Nirvana","location": "NY","year": "2010"},
{"id":"3","name": "Metallica","location": "NY","year": "1980"}]
When i am running the file, I am getting blank values.
Thanks for the help.
The fields must start with uppercase letters.
type bands struct {
Id string `json:"id"`
Name string `json:"name"`
Location string `json:"location"`
Year string `json:"year"`
}
This question already has answers here:
JSON and dealing with unexported fields
(2 answers)
Printing Empty Json as a result [duplicate]
(1 answer)
(un)marshalling json golang not working
(3 answers)
json.Marshal(struct) returns "{}"
(3 answers)
Closed 10 months ago.
As part of an Oauth application, I need to decode some JSON. But I cannot get the object populated. There is no failure, but the data just isn't there. I've tried a bunch of different ways...
I have recreated the problem at http://play.golang.org/p/QGkcl61cmv
import (
"encoding/json"
"fmt"
"strings"
)
type RefreshTokenData struct {
id string `json:"id"`
issued_at string `json:"issued_at"`
scope string `json:"scope"`
instance_url string `json:"instance_url"`
token_type string `json:"token_type"`
refresh_token string `json:"refresh_token"`
signature string `json:"signature"`
access_token string `json:"access_token"`
}
func main() {
var tokenResp = `
{"id":"https://google.com","issued_at":"1423698767063",
"scope":"full refresh_token",
"instance_url":"https://na15.salesforce.com",
"token_type":"Bearer",
"refresh_token":"2os53__CCU5JX_yZXE",
"id_token":"5jSH0Oqm7Q4fc0xkE9NOvW8cA13U",
"signature":"/599EkGVIBsKPFRNkg+58wZ3Q7AFyclvIGvCrxVeyTo=",
"access_token":"sadfasdfasdfasdfdsa"}`
var tokenData RefreshTokenData
decoder := json.NewDecoder(strings.NewReader(tokenResp))
if jsonerr := decoder.Decode(&tokenData); jsonerr != nil {
fmt.Println("****Failed to decode json")
} else {
fmt.Println("****Refresh token: " + tokenData.refresh_token)
}
}
The JSON encoding package works with exported fields only. Capitalize the field names to export them:
type RefreshTokenData struct {
Id string `json:"id"`
Issued_at string `json:"issued_at"`
Scope string `json:"scope"`
Instance_url string `json:"instance_url"`
Token_type string `json:"token_type"`
Refresh_token string `json:"refresh_token"`
Signature string `json:"signature"`
Access_token string `json:"access_token"`
}
playground example