Skip to content

Instantly share code, notes, and snippets.

@hraban hraban/potential_json.go
Last active Jan 7, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.