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
Related
This question already has answers here:
How to parse/deserialize dynamic JSON
(4 answers)
Unmarshal dynamic json content in Go
(1 answer)
Parse dynamic json object
(2 answers)
Closed 1 year ago.
I am calling an API and getting json and don't know how to make a struct for the response I have used JSON-to-GO to get a struct for the response. But the problem is the response is not same every time.
For example I have a struct using the JSON-to-GO :-
type Autogenerated struct {
Response struct {
Results struct {
Status string `json:"status"`
StatusCode int `json:"status_code"`
ResultsData struct {
ResultsCount int `json:"results_count"`
NearbyCount int `json:"nearby_count"`
} `json:"results_data"`
SortData struct {
SortBy string `json:"sort_by"`
} `json:"sort_data"`
ResponseData struct {
Data0 struct {
Name string `json:"name"`
} `json:"data_0"`
Data1 struct {
Name string `json:"name"`
} `json:"data_1"`
} `json:"response_data"`
Time float64 `json:"time"`
} `json:"results"`
} `json:"response"`
}
The Data1 and Data0 can be any more like Data2, Data3.... and I want the Name inside of the Data0, Data1 ....
I am very new to golang, Maybe we can use Map for it but due to being not same all the time I don't know, how to do it. Also there are a lot of filed along with Name which I have not pasted here to keep the question clean.
use map[string]interface{} for Response data type. Data0 to any number os Data0 type fields unmarshal to map as keys data_0, data_1, data_2
ResponseData map[string]interface{} `json:"response_data"`
If your Data coming as a same object for every data_0 ... data_n, then define struct type like below and define map with that type.
//new data type
type Data struct {
Name string `json:"name"`
}
//add this to your Autogenerated struct
ResponseData map[string]Data `json:"response_data"`
or simply add
ResponseData map[string]struct{
Name string `json:"name"`
} `json:"response_data"`
I have trouble unmarshal access the values of a JSON string in my golang service.
I read the documentation for golang but the JSON objects in the examples are all differently formated.
from my api i get the following JSON string:
{"NewDepartment":
{
"newDepName":"Testabt",
"newDepCompany":2,
"newDepMail":"Bla#bla.org"
}
}
in go I defined the following data types:
type NewDepartment struct {
NewDepName string `json:"newDepName"`
NewDepCompany int `json:"newDepCompany"`
NewDepMail string `json:"newDepMail"`
}
type NewDeps struct {
NewDeps []NewDepartment `json:"NewDepartment"`
}
I try to unmarshal the JSON (from request Body) and access the values, but I can't get any results
var data types.NewDepartment
errDec := json.Unmarshal(reqBody, &data)
fmt.Println("AddDepartment JSON string got: " + data.NewDepName)
but it contains no string - nothing is displayed but no error on unmarshaling or Println.
Thanks for the help.
You're almost there.
First update is to make NewDeps.NewDeps a single object, not an array (according to the provided JSON).
The second update is to deserialize JSON into NewDeps, not into NewDepartment.
Working code:
type NewDepartment struct {
NewDepName string `json:"newDepName"`
NewDepCompany int `json:"newDepCompany"`
NewDepMail string `json:"newDepMail"`
}
type NewDeps struct {
NewDeps NewDepartment `json:"NewDepartment"`
}
func main() {
var data NewDeps
json.Unmarshal([]byte(body), &data)
fmt.Println("AddDepartment JSON string got: " + data.NewDeps.NewDepName)
}
https://play.golang.org/p/Sn02hwETRv1
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 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