What is JSON in JavaScript? JSON (JavaScript object notation) is purely a data format; in fact a JSON contains only properties, no methods. It is a very compact text-based format best suited for use with JavaScript. JSON is widely popular outside JavaScript as well, and is used with most modern REST APIs (servers that store and return data for web pages and applications)
We will show you:
- How a JSON data format looks like
- What are data types in JSON
- Show you an example of JSON usage in JavaScript
- How to convert a JSON from and to string
When you work with JavaScript or any other language for a matter of fact, you will work with JSON data. Most of the time programmers use JSON to return data from a REST API, but it can be used to store data as well.
If you are new to programming, you can read our blog and learn what JavaScript is.
How does a JSON format looks like?
Here at CodeBrainer we belive that a picture is worth a 1000 words.
JSON format example
JSON
Here, we can clearly see what is JSON in JavaScript. A format that mimics a JavaScript object (learn more about: What is an Object in JavaScript). JSON is really easy to read for JavaScript developers. In fact, let’s break it down a little bit.
Our JSON and every object starts with curly brackets (“{“). In JSON we also have a lot of arrays. An array starts with square brackets (“[“) for arrays of objects.
A JSON document could also be an array of objects in most cases and also in our case a JSON document starts with a curly bracket and it is an object.
Our object consists of only one property named: bands and it is an array of bands. Futhermore, each band is an object that has all the values for a single band.
JSON requires that you use double quotes around strings and property names. Single quotes are not valid.
You have great examples for double quotes all over our JSON for all the property names like name
, description
, image
… For values you can see that name, description and other values are all written inside double quotes.
As shown above, for numeric values, you do not need quotes, as you can see for the year_established
property for our band.
Reading a JSON file
JSON is a great format as it is readable really well to developers of all kinds, it is very compact, and easy to write. Even for people that see this format for the first time, it is not hard to read the meaning of data.
JSON can be written in expressive or compact/minimized way. A a matter of fact, it is better to have spacing and indentation to see where the data belongs.
Below you have an example of what is JSON in JavaScript and what it looks like when it is minimized:
Reading a minimized JSON takes some practice, but is doable. But you can always use online and offline tools to view a JSON file. I like to use JSON Parser (by Olivier Cuenot) because of its minimalistic UI. Usually when I want to edit a JSON, I use JSON Editor (by Jos de Jong) it has quite a few nice features like sorting and insertion of new records.
Data types in JSON
Data types are basic, but complex enough to prepare even the most complex data values you like.
Types:
- strings,
- numbers,
- booleans,
- arrays,
- object literals
Array and object “type” give JSON it’s power of expression as you can nest objects and arrays in any possible way.
Let us explain what is JSON in JavaScript with an example
The best way to explain what is JSON in JavaScript is with an example. We have JSON for a list of bands as you can see above. The great thing about JSON is that it interacts with JavaScript really well.
Loading JSON data
We want to show you a simple example of a function that loads JSON data, and which you can use on a local source and on a remote source as well.
We start with loadData
, it is a center function that does the heavy lifting for us.
loadData function
JavaScript
The loadData
method goes and gets data for us, using the window.fetch
function. We use then
to read the response and convert it to the JSON using a json
method. The last “then
” is used to call the callback function onLoadCallback.
We build a custom method loadBands
, to load band data.
loadBand function - Load the data about bands
JavaScript
Now you can see our loadData method in action, all we need to specify is the location of the JSON file in our case “bands.json” and the function that consumes the data.
In brief, we now know how to load the data and we can use it in an example.
Working with data
playWithBands
is a method we create to work with the bands data. We specify this method, when the loadBands function is called. The playWithBands
function is called when data is successfully loaded.
playWithBands function - Show the info about bands
JavaScript
First we make a bands
variable, that holds the array of bands. We get the array using a data
parameter. Data is provided for us from the loadData
function (after it loads data for us, it calls the function playWithBands
).
For a simpler example we also make two variables one for each band, metallica
and u2
. You can see that we also set values for both variables. We do this using index 0 for the first record and 1 for the second record. Index for arrays in JavaScript is zero based.
Get the band with specified index
JavaScript
Now that we have variables we can use the values from our JSON.
Printing out the data
To print out the name of the band we simply use the variable of the band and .name
. This returns the value of the name.
Print out the name - console.log
JavaScript
If we want to count the number of bands, we use the bands variable and the array method length
.
Print out number of bands
JavaScript
We can also work with array within the object, for that we use the for-each loop on the albums
array.
Using forEach loop to display albums
JavaScript
forEach
works by calling a function we specify for each item in the array (learn more about loops in JavaScript). We get the value of an album inside the function that has one parameter named album
(this is a name we specify it could be any other name you can think of). When we have the album we can then print out its name (using console.log)
For this example we get the JSON string from a local file. If we want to communicate with a server or store JSON as a variable we need to know how we can convert the values.
Conversions of JSON in JavaScript
We have a great method prepared for us in JavaScript by default. In fact it can make a conversion of JSON data for us from a string and to a string. All we need is to provide object/data for conversion.
Converting JSON to string
We can convert all the objects to a JSON string in order to save data or to send it to the server.
JSON.stringify - convert object to string
JavaScript
In this example we show how to convert the object abba (for a band named abba) into a stringified JSON. Abba is a simple object that only contains the name of the band.
If we print out the string it looks like this:
We can see that a string is written in the same way as we have written it, when we created the JSON file.
Converting string to JSON
Now, we can show the conversion from string. We need to use the JSON.parse function to do that.
JSON.parse - convert string to an object (or an array of objects)
JavaScript
Using parse will return an object that we can use.
Here is a complete example for conversions:
JSON Conversions
JavaScript
Using our example
We built our example using a few files, one for JSON, one for JavaScript and we also used a simple HTML (index.html) to link all of them. Place the code with links to the appropriate files before running your code.
This is the HTML we used:
HTML file for examples
HTML
As explained on the page (index.html) you need to open the debug console within your browser.
If you are new to HTML check our blog on what is HTML as well and if you are more advance take a look at DOM in JavaScript to see how you can display your JSON data on a website.
Checking if JSON is valid
Since the JSON format is very compact it is hard not to miss a bracket, quote, colon… This is why it is very good to use some kind of checker. If you try to parse a crooked JSON with JavaScript, you get an error in the console.
To avoid errors you can check the JSON using an online checker. We like JSONLint the most, since it best explains errors.
For example, if we remove the comma before the second band, we can clearly see where the error is. In fact, if you try to find this error by hand, it will take you some time.
For each error you also get the detailed description:
For sensitive data you should try and find an offline application, or you can build JSONLint yourself, since it is open source.
Conclusion
Now you know what is JSON in JavaScript and you can see that it is a good format for exchanging data between applications, servers, storing data. It works really good with JavaScript and can be easily converted to objects and from object to string as well.
We get asked a lot, how to write a contact form for your web page and contact forms need to send data to a server, so take a look.