What is JSON?
First of all, let’s see what is JSON.
If you are already familiar with XML, JSON is an alternative format to exchange data between a client and a server.
The JSON data above are a valid JSON string that describes a dog breed named Cretan Hound and provides useful information.
This format can be sent from a web server to a web client. Next, the client can parse the JSON data and display the information to the user.
There are popular several tools online that you can use to validate the format of a JSON string.
Reading JSON file with fetch
In the code above, I declared an arrow function to load a URL. The URL represents the file path that contains the JSON information that I want to load in my code.
Next, I pass the URL parameter to the function loadJson. The function loadJson uses the Request Interface to represent a Resource request.
Additionally, I use the fetch API in order to retrieve the data from the resource request.
Since the loadJson function uses the fetch API it will be asynchronous so I am declaring it with the keyword async.
The fetch function will return a promise so in order to read the response form the fetch I will have to use await keyword.
In the logs, you can see that the response object contains useful information such as the status of the request, the body, the type, and others.
It also inherits from its prototype two useful methods.
The text method and the JSON method which we usually use in order to retrieve the data. Both methods are asynchronous and have to be used with the await keyword ahead in order to resolve the promise that is returned.
In this example, I am using the JSON method json() so I use the await keyword for a second time.
Finally, the promise will resolve in the JSON data that can be used as the return value of the loadJson function.
In this section, you can read some extra useful methods that you can use while working with JSON strings
A JSON string can be transferred in text format too. In order to validate and convert the string to a JSON object, we can use the JSON.parse method.
Let’s see the previous example using the response.text method and the JSON.parse method.
If the JSON string is invalid then a SyntaxError exception will be thrown.
On the other hand, we can convert an Object to a JSON string using the JSON.stringify method.
Let’s summarize what you learned in this tutorial
- JSON is a format structure that you can use to exchange data between a client and a server
- You can use JSON.parse method in order to validate and parse a JSON string
- You can convert a JSON object to a JSON string with the method JSON.stringify