When you make a request to a REST API, the data frequently comes back in JSON. This lightweight data-interchange format enables applications to communicate with each other over the network. From a software developer's perspective, understanding how to work with JSON can be crucial. Especially if you're building an app that needs to 'talk' with another app.
In this tutorial we'll show you how to parse JSON in Golang using a built-in library called "encoding/json". Whatever your level this will be easy to follow and a great addition to your engineering toolkit. Let's get started!
Why would you need to parse a JSON-formatted text?
Well, you will need to convert the JSON raw data into an object type that can be used by your application. This means getting its content based on how it's structured.
In JSON, you have strings, numbers, arrays - all glued together with some text. So you'll have to take this apart piece by piece before further processing. For example, before you import them into a database, filter certain items, or display information inside user interfaces for end-users.
How to parse JSON in Go
Now, let's parse some JSON from the Faker API with the following request:
If you copy-paste the above URL into your browser, you'll get a result in JSON. And the response structure will look like this:
The response has the following details:
- "status" — The "OK" status means that the request has been processed successfully.
- "code" — The HTTP code for the status "OK".
- "total" — The total person data returned based on the request, which is 2 in our case.
- "data" — It contains an array of two persons. Each person has "firstname", "lastname", "email", "address", and other info. The "address" itself has "street", "streetname", "city", "country", and other fields.
Next, follow the steps below to parse the above JSON.
Step 1: Declare new custom types using structs
To parse a JSON in Golang, first, you need to declare a custom type using struct. After that, you can map the JSON into that struct.
Now, based on the response, let's write custom types called "Response", "Person", and "Address", with structures as below:
The "Response" struct contains "Status", "Code", "Total", and "Persons". 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.
In line 11, you can see that "Persons" is a slice with elements of type "Person". The same with line 21, notice that the "Address" field is also an element of type "Address".
Step 2: Write a request to the API to get the JSON content.
Let's add the following lines inside main() to make a request to the API. See that we do an http. Get in line 9, and for this, we need to import the "net/http" package.
The Get request returns two values: a response and an error. If there is an error, we use log.Fatal to exit the program. The defer is used to make sure the response body is closed.
Step 3: Parse the JSON
Now, we can parse the response body into the "Response" struct we defined previously. See the below code (line 18-24). First, we need to read the response body before we can do a mapping to the struct. The result is a byte slice if there's no error. After that, we just need to unmarshal from the slice of bytes to an object with the type "Response".
Next, we write code to see the result by printing the parsed JSON (line 26-40). The code will output the details of each person returned in the response.
Here's the result if we run the code:
Yes, it really is as simple as that!
Parsing JSON from an API in Golang can be done relatively easily using the "encoding/json" package and some simple steps outlined above. Hopefully, this article has helped you understand the basics of how to parse JSON from an API in Golang. So now, go ahead and get started parsing your own data. Happy coding! ;)
Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.