Last active
January 7, 2017 23:26
-
-
Save hraban/5b239589581db646810d998e12981cdf to your computer and use it in GitHub Desktop.
safe, human readable nested JSON encoding in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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