Load and parse a JSON data
You can easly grab a json data with a fetch or XMLHTTPRequest and use it. A json data is always represented as a map[string]interface{}. To avoid panic, you must always ensure the data you want has the good type with Type Assertions.
Example with a JSON string
var myjsonstr = `{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}`
func main() {
hogosuru.Init()
if j, err := json.Parse(myjsonstr); hogosuru.AssertErr(err) {
extractdata := j.Map()
if arrayincars, ok := extractdata.(map[string]interface{})["cars"].([]interface{}); ok {
if len(arrayincars) > 0 {
//ensure that the first element is a string
if valuestr, ok := arrayincars[0].(string); ok {
fmt.Printf("First Element in cars is %s\n", valuestr)
}
}
}
if arrayincars, ok := extractdata.(map[string]interface{})["boat"].([]string); ok {
if len(arrayincars) > 0 {
fmt.Printf("First Element in boat is %s\n", arrayincars[0])
}
} else {
fmt.Printf("Boat is not present in json\n")
}
}
}
Execute with headless mode
Result:
Example with a JSON file
The example below use a fetch to retrieve a json file and parse the data. Fetch is a promise and follow the mechanic of promise. This mechanical will be explained in the next guides.
Start with headless mode:
Result:
Thanks to fetch with get the result of get HTTP, Get the text data and parse it with json.
We get the json["headers"]["User-Agent"] data
Factoring Fetch JSON
Of course the fetch example use low level access of promise and fetch. It's verbose but you can control anything.
You can also create some helpers to easily write POST,GET for your apps and the final result will be more friendly.
Here an example of one of my project with factoring fetch:
Last updated