Converting JSON that contains only 1 field of arrays - json

I'm trying to convert a JSON that contains only 1 field which apparently an array to a complex struct in Golang but unfortunately I'm not getting the data back, instead, I got:
{Result:[]}
Anyone knows why? (code below)
package main
import (
"encoding/json"
"fmt"
)
type Account struct {
AccountId string
}
type Response struct {
Result []Account
}
func main() {
input := []byte(`{
"result": [
{"account_id" : "1"},
{"account_id" : "2"},
{"account_id" : "3"},
]
}
`)
var resp Response
json.Unmarshal(input, &resp)
fmt.Printf("%+v\n", resp)
}

use a explicit tag in your stucture type.
type Account struct {
AccountId string `json:"account_id, omitempty"`
}
If you are a novice, keep in mind the JSON size, if is large then use a stream library (jstream or easyjson etc),
other advice is check nullables or omit when they are empty anyway you can use nullable library like https://github.com/guregu/null
Cheers!

Related

Unmarshal JSON with an array

I am trying to Unmarshal the following JSON object which is generated by couchDB and returns for a cURL request in Go, the cURL request code is not mentioned here as it is out of scope of this question and I have assigned it to the variable called mail in the code section.
the JSON data structure:
{
"total_rows": 4,
"offset": 0,
"rows": [{
"id": "36587e5d091a0d49f739c25c0b000c05",
"key": "36587e5d091a0d49f739c25c0b000c05",
"value": {
"rev": "1-92471472a3de492b8657d3103f5f6e0d"
}
}]
}
and here is my code to unmarshel the above JSON object,
package main
import (
"fmt"
"encoding/json"
)
type Couchdb struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []struct {
ID string `json:"id"`
Key string `json:"key"`
Value struct {
Rev string `json:"rev"`
} `json:"value"`
} `json:"rows"`
}
func main() {
mail := []byte(`{"total_rows":4,"offset":0,"rows":[{"id":"36587e5d091a0d49f739c25c0b000c05","key":"36587e5d091a0d49f739c25c0b000c05","value":{"rev":"1-92471472a3de492b8657d3103f5f6e0d"}}]}`)
var s Couchdb
err := json.Unmarshal(mail, &s)
if err != nil {
panic(err)
}
//fmt.Printf("%v", s.TotalRows)
fmt.Printf("%v", s.Rows)
}
and the above code is working fine and you can access the working code here with this link in the Go Play Ground.
I need to get the 36587e5d091a0d49f739c25c0b000c05 value which is the id of rows so I am trying to do it like this
fmt.Printf("%v", s.Rows.ID)
and it returns this error
prog.go:33:25: s.Rows.ID undefined (type []struct { ID string "json:\"id\""; Key string "json:\"key\""; Value struct { Rev string "json:\"rev\"" } "json:\"value\"" } has no field or method ID)
but it works for fmt.Printf("%v", s.Rows) and it returns
[{36587e5d091a0d49f739c25c0b000c05 36587e5d091a0d49f739c25c0b000c05 {1-92471472a3de492b8657d3103f5f6e0d}}]
My ultimate goal is to get 36587e5d091a0d49f739c25c0b000c05 and assign it to GO variable but stuck getting that value using GO.
You have to call :
fmt.Println(s.Rows[0].ID)
You define Rows as slice of struct that means you should iterate Rows with for for execution of values.
for _, item := range s.Rows {
fmt.Println(item.ID)
}

Unmarshal and append to array go

I'm reading a number of JSON files from S3, and want to return them all as one large JSON array. I have a struct matching my JSON data, and a for loop iterating over all objects in my s3 bucket. Each time I read, I unmarshal to my struct array. I want to append to my struct array so that I can get all the JSON data rather than just one file's data. Is there anyway to do this in Golang?
Yes, you should create a temporary array to Unmarshal the contents of each JSON, then append the items to your final result array in order to return the whole collection as one item.
See here an example of doing that.
In your case input would come from each of the S3 files you mention. Also, you would probably put that unmarshal logic in its own function to be able to call it for each input JSON.
package main
import (
"encoding/json"
"fmt"
"log"
)
type Record struct {
Author string `json:"author"`
Title string `json:"title"`
}
func main() {
var allRecords []Record
input := []byte(`[{
"author": "Nirvana",
"title": "Smells like teen spirit"
}, {
"author": "The Beatles",
"title": "Help"
}]`)
var tmpRecords []Record
err := json.Unmarshal(input, &tmpRecords)
if (err != nil) {
log.Fatal(err)
}
allRecords = append(allRecords, tmpRecords...)
fmt.Println("RECORDS:", allRecords)
}
https://play.golang.org/p/ZZGhy4UNhP

Decoding a slice of maps from a JSON string in Golang

Following the Go by Example: JSON tutorial, I see how to work with a basic JSON string:
package main
import (
"encoding/json"
"fmt"
)
type Response struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
str := `{"page": 1, "fruits": ["apple", "peach"]}`
res := Response{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res.Page)
fmt.Println(res.Fruits)
}
// the output looks good here:
// 1
// [apple peach]
I would like to add some complexity to the str data object that I am decoding.
Namely, I would like to add a key with a slice of maps as its value:
"activities": [{"name": "running"}, {"name", "swimming"}]
My script now looks like below example, however, for the life of me, I can not figure out what the correct syntax is in the Response struct in order to get at the values in activities. I know that this syntax isn't correct: Activities []string ... but can not hack my way towards a solution that captures the data I want to display.
package main
import (
"encoding/json"
"fmt"
)
type Response struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
Activities []string `json:"activities"`
}
func main() {
str := `{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name", "swimming"}]}`
res := Response{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res.Page)
fmt.Println(res.Fruits)
fmt.Println(res.Activities)
}
// the script basically craps out here and returns:
// 0
// []
// []
Thanks for any help!
Use []map[string]string:
type Response struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
Activities []map[string]string `json:"activities"`
}
playground example
Always check and handle errors.
The example JSON has a syntax error which is corrected in the playground example.
I know this is an old one, but i've recently written utility for generating exact go type from json input and in similar case you could give it a spin: https://github.com/m-zajac/json2go
For this particular example it generates from json:
{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name": "swimming"}]}
go type:
type Object struct {
Activities []struct {
Name string `json:"name"`
} `json:"activities"`
Fruits []string `json:"fruits"`
Page int `json:"page"`
}

Why struct fields are showing empty?

I am struggling to get the correct output from the following code:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob3 = []byte(`[
{"name": "Platypus", "spec": "Monotremata", "id":25 },
{"name": "Quoll", "spec": "Dasyuromorphia", "id":25 }
]`)
type Animal2 struct {
name string
spec string
id uint32
}
var animals []Animal2
err := json.Unmarshal(jsonBlob3, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", animals)
}
Playground snippet
The struct fields are empty when printed. I am sure there is a dumb mistake somewhere but I am still new to Go and I have been stuck at this for hours. Please help.
This has come up so many times. The problem is that only exported fields can be marshaled/unmarshaled.
Export the struct fields by starting them with capital (upper-case) letters.
type Animal2 struct {
Name string
Spec string
Id uint32
}
Try it on the Go Playground.
Note that the JSON text contains the field names with lowercased text, but the json package is "clever" enough to match them. If they would be completely different, you could use struct tags to tell the json package how they are found (or how they should be marshaled) in the JSON text, e.g.:
type Animal2 struct {
Name string `json:"json_name"`
Spec string `json:"specification"`
Id uint32 `json:"some_custom_id"`
}

JSON unmarshaling with long numbers gives floating point number

I was marshaling and unmarshaling JSONs using golang and when I want to do it with number fields golang transforms it in floating point numbers instead of use long numbers, for example.
I have the following JSON:
{
"id": 12423434,
"Name": "Fernando"
}
After marshal it to a map and unmarshal again to a json string I get:
{
"id":1.2423434e+07,
"Name":"Fernando"
}
As you can see the "id" field is in floating point notation.
The code that I am using is the following:
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
//Create the Json string
var b = []byte(`
{
"id": 12423434,
"Name": "Fernando"
}
`)
//Marshal the json to a map
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
//print the map
fmt.Println(m)
//unmarshal the map to json
result,_:= json.Marshal(m)
//print the json
os.Stdout.Write(result)
}
It prints:
map[id:1.2423434e+07 Name:Fernando]
{"Name":"Fernando","id":1.2423434e+07}
It appears to be that the first marshal to the map generates the FP. How can I fix it to a long?
This is the link to the program in the goland playground:
http://play.golang.org/p/RRJ6uU4Uw-
There are times when you cannot define a struct in advance but still require numbers to pass through the marshal-unmarshal process unchanged.
In that case you can use the UseNumber method on json.Decoder, which causes all numbers to unmarshal as json.Number (which is just the original string representation of the number). This can also useful for storing very big integers in JSON.
For example:
package main
import (
"strings"
"encoding/json"
"fmt"
"log"
)
var data = `{
"id": 12423434,
"Name": "Fernando"
}`
func main() {
d := json.NewDecoder(strings.NewReader(data))
d.UseNumber()
var x interface{}
if err := d.Decode(&x); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded to %#v\n", x)
result, err := json.Marshal(x)
if err != nil {
log.Fatal(err)
}
fmt.Printf("encoded to %s\n", result)
}
Result:
decoded to map[string]interface {}{"id":"12423434", "Name":"Fernando"}
encoded to {"Name":"Fernando","id":12423434}
The JSON standard doesn't have longs or floats, it only has numbers. The json package will assume float64 when you haven't defined anything else (meaning, only provided Unmarshal with an interface{}).
What you should do is to create a proper struct (as Volker mentioned):
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
func main() {
//Create the Json string
var b = []byte(`{"id": 12423434, "Name": "Fernando"}`)
//Marshal the json to a proper struct
var f Person
json.Unmarshal(b, &f)
//print the person
fmt.Println(f)
//unmarshal the struct to json
result, _ := json.Marshal(f)
//print the json
os.Stdout.Write(result)
}
Result:
{12423434 Fernando}
{"id":12423434,"name":"Fernando"}
Playground: http://play.golang.org/p/2R76DYVgMK
Edit:
In case you have a dynamic json structure and wish to use the benefits of a struct, you can solve it using json.RawMessage. A variable of type json.RawMessage will store the raw JSON string so that you later on, when you know what kind of object it contains, can unmarshal it into the proper struct. No matter what solution you use, you will in any case need some if or switch statement where you determine what type of structure it is.
It is also useful when parts of the JSON data will only be copied to the another JSON object such as with the id-value of a JSON RPC request.
Example of container struct using json.RawMessage and the corresponding JSON data:
type Container struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
var b = []byte(`{"type": "person", "data":{"id": 12423434, "Name": "Fernando"}}`)
A modified version of your example on Playground: http://play.golang.org/p/85s130Sthu
Edit2:
If the structure of your JSON value is based on the name of a name/value pair, you can do the same with a:
type Container map[string]json.RawMessage