cannot unmarshal string into Go struct field - json

I have the following (incomplete type) (which is a response from docker API from manifests endpoint v2 schema 1 https://docs.docker.com/registry/spec/manifest-v2-1/)
type ManifestResponse struct {
Name string `json:"name"`
Tag string `json:"tag"`
Architecture string `json:"architecture"`
FsLayers []struct {
BlobSum string `json:"blobSum"`
} `json:"fsLayers"`
History []struct {
V1Compatibility struct {
ID string `json:"id"`
Parent string `json:"parent"`
Created string `json:"created"`
} `json:"v1Compatibility"`
} `json:"history"`
}
While getting the following response:
{ "schemaVersion": 1,
"name": "library/redis",
"tag": "latest",
"architecture": "amd64",
"history": [
{
"v1Compatibility": "{\"id\":\"ef8a93741134ad37c834c32836aefbd455ad4aa4d1b6a6402e4186dfc1feeb88\",\"parent\":\"9c8b347e3807201285053a5413109b4235cca7d0b35e7e6b36554995cfd59820\",\"created\":\"2017-10-10T02:53:19.011435683Z\"}"
}
]
}
While trying to deserialize it using the following snippet of code:
var jsonManResp ManifestResponse
if err = json.NewDecoder(res.Body).Decode(&jsonManResp); err != nil {
log.Fatal(err)
}
I get the following error:
json: cannot unmarshal string into Go struct field .v1Compatibility of type struct { ID string "json:\"id\""; Parent string "json:\"parent\""; Created string "json:\"created\"" }
Full playground code: https://play.golang.org/p/tHzf9GphWX
What might be the problem?

The problem is that v1Compatibility is a string value in the JSON; the value happens to be JSON content, but it's inside a JSON string, so can't be unmarshalled all in one step. You could instead unmarshal it in two passes:
type ManifestResponse struct {
Name string `json:"name"`
Tag string `json:"tag"`
Architecture string `json:"architecture"`
FsLayers []struct {
BlobSum string `json:"blobSum"`
} `json:"fsLayers"`
History []struct {
V1CompatibilityRaw string `json:"v1Compatibility"`
V1Compatibility V1Compatibility
} `json:"history"`
}
type V1Compatibility struct {
ID string `json:"id"`
Parent string `json:"parent"`
Created string `json:"created"`
}
And then:
var jsonManResp ManifestResponse
if err := json.Unmarshal([]byte(exemplar), &jsonManResp); err != nil {
log.Fatal(err)
}
for i := range jsonManResp.History {
var comp V1Compatibility
if err := json.Unmarshal([]byte(jsonManResp.History[i].V1CompatibilityRaw), &comp); err != nil {
log.Fatal(err)
}
jsonManResp.History[i].V1Compatibility = comp
}
Working playground example here: https://play.golang.org/p/QNsu5_63E0

Related

Golang json unmarshall

I'm new in Go. I have json like this:
{
"3415": {
"age": 25,
"name": "Tommy"
},
"3414": {
"age": 21,
"name": "Billy"
}
}
I want to unmarshall it to struct:
type People struct {
Id map[string]PeopleDetails
}
type PeopleDetails struct {
Age int `json:"age"`
Name string `json:"name"`
}
But while I run it, I see that struct return nil value.
I did read some tutorials, but most of them have predefined keys, as You see here "id" e.g. 3415 is different for every new json.
When you have to deal with a "dynamic" json key, the answer is use a map of struct.
You can use the following code:
package main
import (
"encoding/json"
"fmt"
)
// Use the struct pointed by #Adirio
type People map[string]PeopleDetails
type PeopleDetails struct {
Age int `json:"age"`
Name string `json:"name"`
}
var data string = `{"3415":{"age":25,"name":"Tommy"},"3414":{"age":21,"name":"Billy"}}`
func main() {
var p People
if err := json.Unmarshal([]byte(data), &p); err != nil {
fmt.Println(err)
}
fmt.Println(p)
}
GoPlayground: https://play.golang.org/p/kVzNV56NcTd
Try with these types instead:
type People map[string]PeopleDetails
type PeopleDetails struct {
Age int `json:"age"`
Name string `json:"name"`
}

json: cannot unmarshal array into Go value of type main.Data

Json is -
{
"apiAddr":"abc",
"data":
[
{
"key":"uid1",
"name":"test",
"commandList":["dummy cmd"],
"frequency":"1",
"deviceList":["dev1"],
"lastUpdatedBy": "user",
"status":"Do something"
}
]
}
And the code to unmarshall is -
type Data struct {
APIAddr string `json:"apiAddr"`
Data []Template `json:"data"`
}
type Template struct {
Key string `json:"key"`
Name string `json:"name"`
CommandList []string `json:"commandList"`
Frequency string `json:"frequency"`
DeviceList []string `json:"deviceList"`
LastUpdatedBy string `json:"lastUpdatedBy"`
Status string `json:"status"`
}
raw, err := ioutil.ReadFile(*testFile)
if err != nil {
return
}
var testTemplates Data
err = json.Unmarshal(raw, &testTemplates)
if err != nil {
return
}
where testFile is the json file.
I am getting this error
json: cannot unmarshal array into Go value of type main.Data.
Looking at the existing questions in stackoverflow, looks like I am doing all right.Anyone?
Made a few modification and Unmarshaling worked just fine.
package main
import (
"encoding/json"
"fmt"
)
var raw = ` {
"apiAddr":"abc",
"data":
[
{
"key":"uid1",
"name":"test",
"commandList":["dummy cmd"],
"frequency":"1",
"deviceList":["dev1"],
"lastUpdatedBy": "user",
"status":"Do something"
}
]
}`
func main() {
var testTemplates Data
err := json.Unmarshal([]byte(raw), &testTemplates)
if err != nil {
return
}
fmt.Println("Hello, playground", testTemplates)
}
type Data struct {
APIAddr string `json:"apiAddr"`
Data []Template `json:"data"`
}
type Template struct {
Key string `json:"key"`
Name string `json:"name"`
CommandList []string `json:"commandList"`
Frequency string `json:"frequency"`
DeviceList []string `json:"deviceList"`
LastUpdatedBy string `json:"lastUpdatedBy"`
Status string `json:"status"`
}
You can run it in Playground as well: https://play.golang.org/p/TSmUnFYO97-

json: cannot unmarshal string into Go value of type map[string]interface {}

I have been working on converting some crypto pool software over to work with an incompatible coin. I believe I have it all about done. But this error keeps popping up and I just can't seem to figure out what the problem is. Here is my code:
type GetBalanceReply struct {
Unspent string `json:"unspent"`
}
type SendTransactionReply struct {
Hash string `json:"hash"`
}
type RPCClient struct {
sync.RWMutex
Url string
Name string
Account string
Password string
sick bool
sickRate int
successRate int
client *http.Client
}
type GetBlockReply struct {
Difficulty string `json:"bits"`
Hash string `json:"hash"`
MerkleTreeHash string `json:"merkle_tree_hash"`
Nonce string `json:"nonce"`
PrevHash string `json:"previous_block_hash"`
TimeStamp string `json:"time_stamp"`
Version string `json:"version"`
Mixhash string `json:"mixhash"`
Number string `json:"number"`
TransactionCount string `json:"transaction_count"`
}
type GetBlockReplyPart struct {
Number string `json:"number"`
Difficulty string `json:"bits"`
}
type TxReceipt struct {
TxHash string `json:"hash"`
}
type Tx struct {
Gas string `json:"gas"`
GasPrice string `json:"gasPrice"`
Hash string `json:"hash"`
}
type JSONRpcResp struct {
Id *json.RawMessage `json:"id"`
Result *json.RawMessage `json:"result"`
Balance *json.RawMessage `json:"balance"`
Transaction *json.RawMessage `json:"transaction"`
Error map[string]interface{} `json:"error"`
}
func (r *RPCClient) GetPendingBlock() (*GetBlockReplyPart, error) {
rpcResp, err := r.doPost(r.Url, "fetchheaderext", []interface{}{r.Account, r.Password, "pending"})
if err != nil {
return nil, err
}
if rpcResp.Result != nil {
var reply *GetBlockReplyPart
err = json.Unmarshal(*rpcResp.Result, &reply)
return reply, err
}
return nil, nil
}
func (r *RPCClient) GetBlockByHeight(height int64) (*GetBlockReply, error) {
//params := []interface{}{fmt.Sprintf("0x%x", height), true}
params := []interface{}{"-t", height}
return r.getBlockBy("fetch-header", params)
}
Whenever I run that manually in the wallet it displays:
"result": {
"bits": "7326472509313",
"hash": "060d0f6157d08bb294ad30f97a2c15c821ff46236281f118d65576b9e4a0ba27",
"merkle_tree_hash": "36936f36718e134e1eecaef05e66ebc4079811d8ee5a543f36d370335adc0801",
"nonce": "0",
"previous_block_hash": "10f4da59558fe41bab50a15864d1394462cd90836aecf52524f4cbce02a74a27",
"time_stamp": "1520718416",
"version": "1",
"mixhash": "0",
"number": "1011160",
"transaction_count": "1"
}'
But, the code errors out with "json: cannot unmarshal string into Go value of type map[string]interface {}"
Can anyone help me figure this one out? I've been hours on trying to figure it out on my own.
Try changing the type of the Error field to interface{} if you are not sure about the error structure, or change it to string if its always a string.
This should get rid of the error.
The error comes from unmarshaling JSONRpcResp. The input data has something like {error: "this is the error message", ...} and unmarshaling this into a map[string]interface{} will simply not work.

Unmarshal JSON in go with different types in a list

I have trouble unmarschaling a JSON contruct:
{
"id": 10,
"result": [
{
"bundled": true,
"type": "RM-J1100"
},
[
{
"name": "PowerOff",
"value": "AAAAAQAAAAEAAAAvAw=="
},
{
"name": "Input",
"value": "AAAAAQAAAAEAAAAlAw=="
}
]
]
}
I actually need the second slice item from the result.
My current attempt is
type Codes struct {
Id int32 `json:"id"`
Result []interface{} `json:"result"`
}
type ResultList struct {
Info InfoMap
Codes []Code
}
type InfoMap struct {
Bundled bool `json:"bundled"`
Type string `json:"type"`
}
type Code struct {
Name string `json:"name"`
Value string `json:"value"`
}
the output is like:
{10 {{false } []}}
but I also tried to use this:
type Codes struct {
Id int32 `json:"id"`
Result []interface{} `json:"result"`
}
the output is okay:
{10 [map[type:RM-J1100 bundled:true] [map[name:PowerOff value:AAAAAQAAAAEAAAAvAw==] map[name:Input value:AAAAAQAAAAEAAAAlAw==]]]}
I can also reference the Result[1] index:
[map[name:PowerOff value:AAAAAQAAAAEAAAAvAw==] map[name:Input value:AAAAAQAAAAEAAAAlAw==]]
But I fail to convert the interface type to any other Type which would match. Can anybody tell me how to do interface conversion. And what approach would be the "best".
One option would be to unmarshal the top level thing into a slice of json.RawMessage initially.
Then loop through the members, and look at the first character of each one. If it is an object, unmarshal that into your InfoMap header struct, and if it is an array, unmarshal it into a slice of the Code struct.
Or if it is predictable enough, just unmarshal the first member to the one struct and the second to a slice.
I made a playground example of this approach.
type Response struct {
ID int `json:"id"`
RawResult []json.RawMessage `json:"result"`
Header *Header `json:"-"`
Values []*Value `json:"-"`
}
type Header struct {
Bundled bool `json:"bundled"`
Type string `json:"type"`
}
type Value struct {
Name string `json:"name"`
Value string `json:"value"`
}
func main() {
//error checks ommitted
resp := &Response{}
json.Unmarshal(rawJ, resp)
resp.Header = &Header{}
json.Unmarshal(resp.RawResult[0], resp.Header)
resp.Values = []*Value{}
json.Unmarshal(resp.RawResult[1], &resp.Values)
}
(I will not point out how horrific it is this JSON struct, but as always: sXXt happens)
You can convert your struct like this, by using a cycle of JSON Marshal / Unmarshal. Code follows:
package main
import (
"encoding/json"
"log"
)
const (
inputJSON = `{
"id": 10,
"result": [
{
"bundled": true,
"type": "RM-J1100"
},
[
{
"name": "PowerOff",
"value": "AAAAAQAAAAEAAAAvAw=="
},
{
"name": "Input",
"value": "AAAAAQAAAAEAAAAlAw=="
}
]
]
}`
)
type Codes struct {
Id int32 `json:"id"`
Result [2]interface{} `json:"result"`
}
type Result struct {
Info InfoMap
Codes []Code
}
type InfoMap struct {
Bundled bool `json:"bundled"`
Type string `json:"type"`
}
type Code struct {
Name string `json:"name"`
Value string `json:"value"`
}
func main() {
newCodes := &Codes{}
err := json.Unmarshal([]byte(inputJSON), newCodes)
if err != nil {
log.Fatal(err)
}
// Prints the whole object
log.Println(newCodes)
// Prints the Result array (!)
log.Println(newCodes.Result)
if len(newCodes.Result) != 2 {
log.Fatal("Invalid Result struct")
}
// Marshal and Unmarshal data to obtain the code list
byteCodeList, _ := json.Marshal(newCodes.Result[1])
codeList := make([]Code, 0)
err = json.Unmarshal(byteCodeList, &codeList)
if err != nil {
log.Fatal("Invalid Code list")
}
// Prints the codeList
log.Println(codeList)
}
Test it on playground.

Creating JSON representation from Go struct

I am trying to create a JSON string from a struct:
package main
import "fmt"
func main() {
type CommentResp struct {
Id string `json: "id"`
Name string `json: "name"`
}
stringa := CommentResp{
Id: "42",
Name: "Foo",
}
fmt.Println(stringa)
}
This code prints {42 foo}, but I expected {"Id":"42","Name":"Foo"}.
What you are printing is fmt's serialization of the CommentResp struct. Instead, you want to do is use json.Marshal to get the encoded JSON repsentation:
data, err := json.Marshal(stringa)
if err != nil {
// Problem encoding stringa
panic(err)
}
fmt.Println(string(data))
https://play.golang.org/p/ogWKQ3M6tb
Also, your json struct tags are not valid; there cannot be a space between : and the quoted string:
type CommentResp struct {
Id string `json:"id"`
Name string `json:"name"`
}
https://play.golang.org/p/eQiyTk6-vQ