3

I'm testing out how to unmarshal a json response from an API I'm using.

The json looks something like the following;

body := []byte(`[
    {"name":"Name1", "value":100.00},
    {"name":"Name2", "value":200.00}
]`)

I've searched around for various ways to do this, but fail to get this to work. The unmarshal returns zero values. I also get an error "unexpected end of JSON input" (I've removed the error handling in the example).

Full code example - https://play.golang.org/p/VMdWuAm6HS

Reference:

  1. https://godoc.org/encoding/json#RawMessage
  2. Golang json Unmarshal "unexpected end of JSON input"
  3. How to unmarshal json into interface{} in golang?

1 Answer 1

2

Your input JSON can be modeled with a simple []Obj where Obj is your type:

type Obj struct {
    Name  string  `json:"name"`
    Value float32 `json:"value"`
}

Nothing else is required, really:

body := []byte(`[
    {"name":"Name1", "value":100.00},
    {"name":"Name2", "value":200.00}]`)

var res []Obj
err := json.Unmarshal(body, &res)
fmt.Printf("%#v\n%v\n", res, err)

Output contains the data from the input JSON (try it on the Go Playground):

[]main.Obj{main.Obj{Name:"Name1", Value:100}, main.Obj{Name:"Name2", Value:200}}
<nil>

Back to your code:

Where you're going wrong is that you use this model:

type Obj struct {
    Name string `json:"name"`
    Value float32 `json:"value"`
}

type Result struct {
    Data json.RawMessage
}

var res []Result

But this res variable would model the following JSON:

[
    {"Data":{"name":"Name1", "value":100.00}},
    {"Data":{"name":"Name2", "value":200.00}}
]

I think you can see the difference: the elements of the array here are JSON Objects with a "Data" field, which then are modeled with your Obj. This input JSON is then properly parsed with your original parsing code, you can try it on the Go Playground:

[{{"name":"Name1", "value":100.00}} {{"name":"Name2", "value":200.00}}] 
&main.Obj{Name:"Name1", Value:100} 
&main.Obj{Name:"Name2", Value:200}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.