Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
JSON stands for JavaScript Object Notation.
It’s a popular data-interchange format that has many uses.
In this article, we’ll take a look at how to use JSON.
Syntax Validation
We can validate the syntax for JSON with many tools.
Many IDEs like WebStorm and text editors like Visual Studio Code have JSON validation capabilities built-in.
There are also many websites that let us validate our JSON code.
They include:
They all provide syntax highlighting and will show errors if there are any errors with the syntax.
JSON as a Document
JSON can be used as documents. We just have to save it with the .json
extension to use them.
The JSON MediaType
JSON has its own MIME type, which is application/json
.
It’s a standard Internet media type that we can use for communication.
JSON Data Types
JSON lets us add values with a few data types into our object.
They include numbers, characters and strings, and booleans. These are primitive data types, which are the most basic data types.
We can also add the array composite data type, which is something composed of primitive data types.
In JSON, the allowed data types are:
- Object
- String
- Number
- Boolean
- Null
- Array
The JSON object data type is the root data type.
The root of a piece of JSON data is either an object or an array.
For instance, we can write:
{
"person": {
"name": "james smith",
"heightInCm": 180,
"head": {
"hair": {
"color": "brown",
"length": "short",
"style": "A-line"
},
"eyes": "blue"
}
}
}
to add an object with key-value pairs that describe a person.
It has the person
key which is set to an object value.
There are also other object values like head
and hair
.
heightInCm
has a number value.
JSON String Data Type
One of the basic JSON data types is a string.
A string has any text data.
A JSON string can be comprised of any Unicode character.
A string must always be enclosed in double-quotes.
For example, we can’t write:
{
'title': 'title.',
'body': 'body.'
}
but we can write:
{
"title": "title.",
"body": "body."
}
If we want to add double quotes in a string, we can use the backslash to escape them.
For instance, we can write:
{
"promo": "Say \"cheese!\""
}
to add the double quotes inside the string by adding a backslash before it.
If we want to add a backslash into a string, then we have to add 2 backslashes:
{
"path": "C:\\Program Files"
}
Other characters that have to escaped include:
- / (forward slash)
- b (backspace)
- f (form feed)
- t (tab)
- n (newline)
- r (carriage return)
- u followed by hexadecimal characters
For example, we can use them by writing:
{
"story": "\t Once upon a time, \n there was a prince."
}
We added the tab character with \t
and a newline with \n
.
Conclusion
We can validate JSON syntax with many tools.
Also, there are a few data types that are supported in JSON.
Special characters also have to be escaped.