Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access fields of a JSON in GO

Tags:

json

printing

go

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?

like image 926
Nighthee Avatar asked Feb 26 '16 19:02

Nighthee


People also ask

How do I access JSON in Go?

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.

How do you access fields in JSON objects?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do I read a JSON file in Golang?

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.


1 Answers

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

like image 173
deepak Avatar answered Oct 11 '22 01:10

deepak