Created
April 15, 2018 20:12
-
-
Save mathcass/cf6032014ad2b975033e12da1b74a805 to your computer and use it in GitHub Desktop.
Example of unmarshalling a JSON string in Go "lazily" to ensure that you at least decode some of the items in the event of an error.
This file contains 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
// Demonstrates how to do "lazy" JSON Unmarshaling if you suspect that the main | |
// JSON container is formatted correctly but some sub-items may not be formatted | |
// correctly. | |
package main | |
import ( | |
"encoding/json" | |
"log" | |
) | |
// CoolData represents cool data | |
type CoolData struct { | |
Name string `json:"name"` | |
Cool string `json:"cool"` | |
} | |
var correctData = `[ | |
{"name": "Cass", "cool": "true"}, | |
{"name": "Kale", "cool": "true"} | |
]` | |
var incorrectData = `[ | |
{"name": "Cass", "cool": "true"}, | |
{"name": "Kale", "cool": true} | |
]` | |
func main() { | |
// Unmarshal is great when the whole payload is correct | |
var correctItems []CoolData | |
_ = json.Unmarshal([]byte(correctData), &correctItems) | |
log.Println("This is decoded correctly: ", correctItems) | |
err := json.Unmarshal([]byte(incorrectData), &correctItems) | |
log.Println("This was not Unmarshaled correctly because: ", err) | |
log.Println("This is also wasteful because not all of the items in the list were encoded incorrectly, only one of them") | |
var maybeCoolData []json.RawMessage | |
_ = json.Unmarshal([]byte(correctData), &maybeCoolData) | |
log.Println("This is decoded as a list of raw JSON: ", maybeCoolData) | |
var allCorrectItems []CoolData | |
for _, item := range maybeCoolData { | |
var coolItem CoolData | |
_ = json.Unmarshal(item, &coolItem) | |
allCorrectItems = append(allCorrectItems, coolItem) | |
} | |
log.Println("We end up with all the correct items: ", allCorrectItems) | |
_ = json.Unmarshal([]byte(incorrectData), &maybeCoolData) | |
var someCorrectItems []CoolData | |
for _, item := range maybeCoolData { | |
var maybeCoolItem CoolData | |
err = json.Unmarshal(item, &maybeCoolItem) | |
if err != nil { | |
log.Println("Unable to Unmarshal CoolData because: ", err) | |
continue | |
} | |
someCorrectItems = append(someCorrectItems, maybeCoolItem) | |
} | |
log.Println("We end up with some of the correct items: ", someCorrectItems) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment