Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active January 7, 2017 23:26
Show Gist options
  • Save hraban/5b239589581db646810d998e12981cdf to your computer and use it in GitHub Desktop.
Save hraban/5b239589581db646810d998e12981cdf to your computer and use it in GitHub Desktop.
safe, human readable nested JSON encoding in Go
package main
import (
"encoding/json"
)
// PotentialJSON acts as a JSON encoding wrapper for []byte. The encoding is
// tentative:
//
// * if the contents already happen to be valid JSON, then it is represented
// verbatim. I.e.: not encoded at all.
//
// * otherwise the default encoding (i.e. base64) is used.
//
// This is useful for human readable "nested-json" output.
type PotentialJSON []byte
func isValidJSON(b []byte) bool {
var v interface{}
return json.Unmarshal(b, &v) == nil
}
func (p PotentialJSON) MarshalJSON() ([]byte, error) {
b := []byte(p)
if isValidJSON(b) {
return b, nil
} else {
return json.Marshal(b)
}
}
package main
import (
"encoding/json"
"os"
)
func ExamplePotentialJSON() {
type TestType struct {
A, B, C, D PotentialJSON
}
b, _ := json.MarshalIndent(TestType{
A: PotentialJSON(`this is not JSON`),
B: PotentialJSON(`"this is JSON"`),
C: PotentialJSON(`null`),
D: PotentialJSON(`{"nestedJSON": true}`),
}, "", " ")
os.Stdout.Write(b)
// Output:
// {
// "A": "dGhpcyBpcyBub3QgSlNPTg==",
// "B": "this is JSON",
// "C": null,
// "D": {
// "nestedJSON": true
// }
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment