![]() Parsing JSON from an API in Golang can be done relatively easily using the "encoding/json" package and some simple steps outlined above. Yes, it really is as simple as that! Wrapping up The code will output the details of each person returned in the response.Īddress: 893 Heaney Orchard Valentin Avenue 219 SpencerboroughĪddress: 91276 Hiram Creek Apt. Next, we write code to see the result by printing the parsed JSON (line 26-40). ![]() After that, we just need to unmarshal from the slice of bytes to an object with the type "Response". The result is a byte slice if there's no error. First, we need to read the response body before we can do a mapping to the struct. Now, we can parse the response body into the "Response" struct we defined previously. ![]() The defer is used to make sure the response body is closed. If there is an error, we use log.Fatal to exit the program. The Get request returns two values: a response and an error. Get in line 9, and for this, we need to import the "net/http" package. Let's add the following lines inside main() to make a request to the API. Step 2: Write a request to the API to get the JSON content. The same with line 21, notice that the "Address" field is also an element of type "Address". In line 11, you can see that "Persons" is a slice with elements of type "Person". Notice that for the "Persons" field, we use a field tag `json:"data"` to help Go examine which field in the JSON is mapped to this field in the struct. The "Response" struct contains "Status", "Code", "Total", and "Persons". Now, based on the response, let's write custom types called "Response", "Person", and "Address", with structures as below: After that, you can map the JSON into that struct. To parse a JSON in Golang, first, you need to declare a custom type using struct. Step 1: Declare new custom types using structs Next, follow the steps below to parse the above JSON. The "address" itself has "street", "streetname", "city", "country", and other fields. Each person has "firstname", "lastname", "email", "address", and other info.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |