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"`
}
Related
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.
This question already has answers here:
JSON and dealing with unexported fields
(2 answers)
(un)marshalling json golang not working
(3 answers)
Closed 4 years ago.
Begining to study golang.
Task: Get Json and Unmarshall it.
But I get mistake:
Json tag but not exported
How to make unexported fields become exported and then implement it using methods?
Here is the code:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Time struct {
time
}
type time struct {
id string `json:"$id"`
currentDateTime string `json:"currentDateTime,string"`
utcOffset float64 `json:"utcOffset,string"`
isDayLightSavingsTime bool `json:"isDayLightSavingsTime,string"`
dayOfTheWeek string `json:"dayOfTheWeek,string"`
timeZoneName string `json:"timeZoneName,string"`
currentFileTime float64 `json:"currentFileTime,string"`
ordinalDate string `json:"ordinalDate,string"`
serviceResponse string `json:"serviceResponse,string"`
}
func (t *Time) GetTime() (Time, error) {
result := Time{}
return result, t.Timenow(result)
}
func (t *Time) Timenow(result interface{}) error {
res, err := http.Get("http://worldclockapi.com/api/json/utc/now")
if err != nil {
fmt.Println("Cannot get Json", err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Cannot create Body", err)
}
defer res.Body.Close()
var resultJson interface{}
return json.Unmarshal(body, &resultJson)
}
func main() {
var a Time
t, err := a.GetTime()
if err != nil {
fmt.Println("Error ", err)
}
fmt.Println("Time:", t)
}
Please explain in details whats wrong with struct and how to get right response?
You're adding a JSON tag to a field that isn't exported.
Struct fields must start with upper case letter (exported) for the JSON package to see their value.
struct A struct {
// Unexported struct fields are invisible to the JSON package.
// Export a field by starting it with an uppercase letter.
unexported string
// {"Exported": ""}
Exported string
// {"custom_name": ""}
CustomName string `json:"custom_name"`
}
The underlying reason for this requirement is that the JSON package uses reflect to inspect struct fields. Since reflect doesn't allow access to unexported struct fields, the JSON package can't see their value.
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:
json.Marshal(struct) returns "{}"
(3 answers)
Closed 6 years ago.
I have a json:
{"code":200,
"msg":"success",
"data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}
and i define a struct :
type Result struct {
code int
msg string `json:"msg"`
data map[string]interface{} `json:"data"`
}
for this code:
var res Result
json.Unmarshal(body, &res)
fmt.Println(res)
the output is: {0 map[]}
i want to get url in data, how to get it?
You should export fields (code, msg, data) for Result by capitalizing the first letter of fields (Code, Msg, Data) to access (set/get) them:
package main
import (
"encoding/json"
"fmt"
)
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}
func main() {
str := `{"code":200,"msg":"success","data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}`
var res Result
err := json.Unmarshal([]byte(str), &res)
fmt.Println(err)
fmt.Println(res)
}
Play the code on https://play.golang.org/p/23ah8e_hCa
Related question: Golang - Capitals in struct fields
This question already has an answer here:
How Do I Parse a JSON file into a struct with Go
(1 answer)
Closed 7 years ago.
I cannot get the standard library's encoding/json package to work for decoding JSON objects. Here's a minimal example:
b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)
This prints:
contents = {groups:[]}
err = nil
But I expect:
contents = {groups:[{name:foo} {name:bar}]}
What am I doing wrong?
The field names have to start with a capital letter:
type Group struct{ Name string }
var contents struct {
Groups []Group
}