The JSON that I am at tempting to parse is very basic and looks like this.
{"id": 3, "title":"Test"}
The following is the code that I am attempting to use for creating and parsing the JSON.
package main
import (
"fmt"
"encoding/json"
)
type Config struct{
id int
title string
}
func main() {
var jsonStr = []byte(`{"id": 3, "title":"Test"}`)
var conf Config
err := json.Unmarshal(jsonStr, &conf)
if err!=nil{
fmt.Print("Error:",err)
}
fmt.Println(conf)
fmt.Println(string(jsonStr))
}
Been looking over a lot of different code examples and can't see what I'm doing wrong. When I attempt to run this, this is what I get as a return.
{0 }
{"id": 3, "title":"Test"}
I have verified that the JSON is valid, but continue to get an empty return when attempting to use json.Unmarshal. Any ideas on what I am missing so that I can get this JSON parsed?
EDIT: Looks like I can get this to work if I capitalize the titles (Id, Title). Unfortunately the return I am testing for is a return from an API which returns everything in lowercase. I need to be able to parse this JSON with lowercase titles as listed above.
Your Config
struct's fields need to be exported (upper-case), but the keys in your JSON object may remain lower-case.
See here: http://play.golang.org/p/0A5tkCkSO5
Please consult the JSON package documentation, it is worth the read. While Amit already addressed the export issue I will address the following:
EDIT: Looks like I can get this to work if I capitalize the titles (Id, Title). Unfortunately the return I am testing for is a return from an API which returns everything in lowercase. I need to be able to parse this JSON with lowercase titles as listed above.
As you might imagine, the authors of encoding/json
have thought of that, so again I encourage you to consult the documentation next time. The solution is this (Example on playground):
type Config struct {
Id int `json:"id"`
Title string `json:"title"`
}