0

Is it possible to make marshall fail inside getJSONStr function after receiving some string?

package main

import (
   "fmt"
   "encoding/json"
)

type obj struct {
  Name string            `json:"name"`
}

func getJSONStr(s string) (*string, error) {
 t := new(obj)
 t.Name = s
 b, err := json.Marshal(t)
 if err != nil {
    return nil, err
 }
 str := string(b)
 return &str, nil
}

func main() {
   str, err := getJSONStr("VALIDATE")
   fmt.Println("str",*str)
   fmt.Println("err",err)
}

I've been trying to make it but with no success.

J. Ordaz
  • 415
  • 6
  • 16
  • See related: [Can marshalling a map\[string\]string to json return an error?](https://stackoverflow.com/questions/49239367/can-marshalling-a-mapstringstring-to-json-return-an-error/49240146#49240146) – icza Sep 06 '18 at 20:30

2 Answers2

1

You can implement json.Marshaler for either obj or the the specific field inside obj. This marshaler can check the value of the field and return an error. Here's an example with a custom marshaler added for the Name field which fails if Name is "Boom!"

type NameWithValidation string

func (s NameWithValidation) MarshalJSON() ([]byte, error) {
    if string(s) == "Boom!" {
        return nil, fmt.Errorf("Name '%s' failed validation", s)
    }
    return json.Marshal(string(s))
}

type obj struct {
    Name NameWithValidation `json:"name"`
}

When marshalling, json.Marshal() checks if the type implements json.Marshaler and if that's true, it calls MarshalJSON() on them instead of trying to marshal the item itself.

svsd
  • 1,831
  • 9
  • 14
0

From the Godocs

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

So if you were to modify your struct to include any of these types and attempt to marshal it you would then get an error.

Community
  • 1
  • 1
Jamie Davenport
  • 351
  • 3
  • 10