Home > front end >  Json decode always executing irrespective of the structure
Json decode always executing irrespective of the structure

Time:12-08

Please help me with the below as always the condition is exceuted irrespective of the type of json response. This is a sample public url returning json and we just log the title if the response conforms to the structure. However what ever json response is coming the code is going inside the condition(err ==nil). The json Decoder should be checking the structure of the response if i am not wrong.

my code complete below

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type response struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}

func main() {
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        log.Fatalln(err)
    }
    var actual response

    if err = json.NewDecoder(resp.Body).Decode(&actual); err == nil {
        fmt.Printf("anotherLink from docker container: %s", actual.Title)

    }

CodePudding user response:

By default, object keys which don't have a corresponding struct field are ignored. Use DisallowUnknownFields to cause the decoder to return an error for unknown keys.

d := json.NewDecoder(resp.Body)
d.DisallowUnknownFields()
if err = d.Decode(&actual); err == nil {
    fmt.Printf("anotherLink from docker container: %s", actual.Title)

}

The problem with this approach is that the struct type must include every field sent by the server. Decode will fail if the server adds a new field in the future.

A better option is to reject the response if specified fields are not set.

if err = json.NewDecoder(resp.Body).Decode(&actual); err != nil || actual.UserID == "" {
    // Handle bad response.
}
  • Related