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
}
Related
This question already has answers here:
Custom unmarshaling a struct into a map of slices
(1 answer)
How to parse a complicated JSON with Go unmarshal?
(3 answers)
golang | unmarshalling arbitrary data
(2 answers)
How to parse JSON in golang without unmarshaling twice
(3 answers)
Decoding generic JSON objects to one of many formats
(1 answer)
Closed 9 months ago.
I'm scraping Binance API for candle price data. The Binance API provides the said data as json array. Each element of the array is a list representing candle and does not contain elements of the same type, however each list contains the same set of types: strings and ints, to be precise. Look at the raw data of this for instance: https://api.binance.com/api/v3/klines?symbol=ZECUSDT&interval=1h&limit=10&startTime=1653001200000
How do I automatically unmarshal such json into struct? Is using reflect the only option here?
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
type PriceData struct {
Data map[int]Price
}
type Price struct {
TradeStart uint64 `json:"0"` // tried without json tags
PriceOpen string `json:"1"`
PriceHigh string `json:"2"`
PriceLow string `json:"3"`
PriceClose string `json:"4"`
TradeEnd uint64 `json:"6"`
// QuoteVolume string // tried with these fields as well
// NumberOfTrades uint64
// TakerBuyBaseVolume string
// TakerBuyQuoteVolume string
}
func main() {
url := "https://api.binance.com/api/v3/klines?symbol=ZECUSDT&interval=1h&limit=10&startTime=1653001200000" // tried /api/v1 as well
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// var priceData map[int]Price // -- tried
// var priceData []Price // -- tried
// var priceData PriceData // -- tried
// var priceData []interface{} -- works fine, but will need to use reflection
var priceData []Price
if err = json.Unmarshal(content, &priceData); err != nil {
log.Fatal(err)
}
interupt := make(chan os.Signal, 1)
signal.Notify(interupt, syscall.SIGTERM, syscall.SIGINT)
<-interupt
}
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.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:
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.Marshal(struct) returns "{}"
(3 answers)
JSON and dealing with unexported fields
(2 answers)
(un)marshalling json golang not working
(3 answers)
Parsing JSON in Golang doesn't Populate Object [duplicate]
(1 answer)
Printing Empty Json as a result [duplicate]
(1 answer)
Closed 2 months ago.
I have json which is not decoded to struct.
I know that error somewhere in my code, but I'm stuck and do not know where the error is and what am I doing wrong
Help me please, here is my code:
type GOOGLE_JSON struct {
code string `json:"code"`
clientId string `json:"clientId"`
redirectUri string `json:"redirectUri"`
}
body := []byte(`{"code":"111","clientId":"222","redirectUri":"333"}`)
//google_json := GOOGLE_JSON{}
var google_json GOOGLE_JSON
err := json.Unmarshal(body, &google_json)
if err != nil {
fmt.Println(err)
}
fmt.Println(google_json)
example here
I've found error
was
type GOOGLE_JSON struct {
code string `json:"code"`
clientId string `json:"clientId"`
redirectUri string `json:"redirectUri"`
}
must be capital letters
type GOOGLE_JSON struct {
Code string `json:"code"`
ClientId string `json:"clientId"`
RedirectUri string `json:"redirectUri"`
}
I was inattentive
Code // <- exported
ClientId // <- exported
RedirectUri // <- exported
code // <-- not exported
clientId // <-- not exported
redirectUri // <-- not exported