Sitemap

What is JSON?

3 min readNov 30, 2022

--

Press enter or click to view image in full size

JSON (JavaScript Object Notation) is a lightweight data interchange text only format used for storing and transporting data. It is easy for humans to read and write.

JSON syntax is derived on JavaScript object notation syntax. However any programming language can be used to write code that reads and produces JSON data such as C, C++, C#, Java, JavaScript, Perl, Python, and many others.

Get Nethmi Warnakula’s stories in your inbox

Join Medium for free to get updates from this writer.

Example :

//JSON syntax
const Student = {
"name" : "Natasha",
"age" : 18,
"city" : "Kalutara",
}

JSON syntax rules

  • Data should be in key / value pairs
//JSON data
"name" : "Natasha"
  • Data is separated by commas.
  • The key and value must be separated by a colon (:) symbol.
  • No comments (// or /* */) are allowed in JSON data.
  • Curly braces hold objects (Objects can have multiple key/value pairs)
//JSON object
const Student = {
"name" : "Natasha",
"age" : 18,
"city" : "Kalutara"
}
  • Square braces hold arrays (JSON array is a list of objects)
// JSON array
[ "Natasha", "Kasun", "Michell"]

// JSON array containing objects
const StudentList = [
{"name" : "Natasha", age : 18, "city" : "Kalutara"},
{"name" : "Kasun", age : 16, "city" : "Colombo"},
{"name" : "Michell", age : 15, "city" : "Matara"}
]

Accessing JSON Data

//JSON data
const student = {
"name" : "Natasha",
"age" : 18,
"city" : "Kalutara",
}

//access using dot notation
var name = student.name;

//access using square bracket syntax
var name = student[name];

JSON data types

Press enter or click to view image in full size

JSON data as Strings

We can use JSON data as a string value and assign it to a variable. As JSON is a text-based format, it is possible to handle as a string in most programming languages

const Student = '{"name": "Natasha", "age": 18, "city": "Kalutara"}';

Converting JSON string to JavaScript Object

JSON.parse() is used to convert the JSON data into a JavaScript object.

// json object
const jsonData = '{ "name": "Natasha", "age": 18 }';

// converting to JavaScript object
const obj = JSON.parse(jsonData);

Converting a JavaScript object into a JSON string

JSON.stringify() is used to convert a JavaScript object to JSON type

// JavaScript object
const obj = { "name": "Natasha", "age": 18 };

// converting to JSON
const jsonData = JSON.stringify(obj);

Features of JSON

  • Easy to learn, easy to read, and easy to understand
  • Faster parsing process
  • Language-independent
  • Lightweight

JSON vs XML

JSON and XML are widely used as data interchange formats, and as a technique to store structured data.

Press enter or click to view image in full size

JSON vs JavaScript Objects

The JSON data format is derived from the JavaScript object structure. But the similarity ends there.

Press enter or click to view image in full size

--

--