Hi everyone I'm trying to see what the proper way of accessing fields of a json object from a http.get request in go.
I first do an http.get call get the JSON and then print it (which works) but is there a way to access just a field?
for example:
response, err:= http.Get("URL")
//Error checking is done between
contents, err:=ioutil.Readall(response.Body)
//Now at this point I have a json that looks like
{"id": "someID",
"name": "someName",
"test": [{"Name":"Test1",
"Result": "Success"},
{"Name":"Test2",
"Result": "Success"},
{...},
]}
Is there a way to only print the "test" of the Json? What is the proper way of accessing that field?
In the main.go file, you'll add a main function to run your program. Next, you'll add a map[string]interface{} value with various keys and types of data. Then, you'll use the json. Marshal function to marshal the map data into JSON data.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.
You may want to try gabs container, if you are not sure how depth JSON hierarchy can be. Have a look at below resources
https://github.com/Jeffail/gabs https://godoc.org/github.com/Jeffail/gabs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With