How to Check String is In Json Format in Go

Created
Modified

Using Unmarshal Function

The following example should cover whatever you are trying to do:

package main

import (
  "encoding/json"
  "fmt"
)

func isJson(s string) bool {
  var js json.RawMessage
  return json.Unmarshal([]byte(s), &js) == nil
}
func isQuotedJson(s string) bool {
  var js map[string]interface{}
  return json.Unmarshal([]byte(s), &js) == nil
}

func main() {
  s := `{"key":"value"}`

  b := isJson(s)
  fmt.Println(b)

  b = isQuotedJson(s)
  fmt.Println(b)
}
true
true

Using Standard Library Function

Standard encoding/json library contains json.Valid function starting from go 1.9. This function may be used for checking whether the provided string is a valid json:

package main

import (
  "encoding/json"
  "fmt"
)

func main() {
  s := `{"key":"value"}`

  b := json.Valid([]byte(s))
  fmt.Println(b)
}
true

Related Tags

#check# #json#