JSON (JavaScript Object Notation) is a data representation format used widely across the internet for things such as APIs and configuration files. JSON is popular because it is lightweight and easy to read/write compared to languages like XML.
The JSON syntax is similar to the JavaScript object notation; however, the JSON format is text only. JSON is language-independent; thus, you can use it to send data across multiple computers and programming languages.
The Relationship Between JSON And JavaScript
The most apparent similarity between JSON and JavaScript is that JavaScript is a part of JSON’s name. The name similarity is so because JSON uses JavaScript’s syntax and its encoding to a large extent; anything you write in JSON is valid JavaScript.
JSON is popular because it eliminates the need for the reading between tags that XML makes users go through; this makes the data you send using JSON understandable to human eyes.
There are two broad sets of data types in JavaScript; the first is primitive values like strings, numbers, and booleans. Also, another set of data types is known as objects, including objects, arrays, and dates. JavaScript reads JSON data as an object type, meaning you can apply methods meant for regular objects on JSONs.
const sampleJSON = {
"firstName" : "Stephen",
"lastName" : "Nabena"
}
console.log(typeof sampleJSON) // this value returned would be Object
Converting JSON To String
A string in JavaScript is a primitive value type used to represent textual data; usually, you should enclose them in single or double quotes (” or “”). There are times when you need to convert the content of a JSON object into a string; you can do that using the JSON.stringify() method and passing the JSON object as an argument.
Note that using the stringify method converts every content of the JSON object into a string; this is including all the symbols and parentheses. This is how to convert a JSON to a string:
const sampleJSON = {
"firstName" : "Stephen",
"lastName" : "Nabena"
}
const toString = JSON.stringify(sampleJSON);
console.log(toString) // the result will be a flat string that looks like {"firstName":"Stephen","lastName":"Nabena"}
Converting String To JSON
Sometimes you would need to convert stringed data into JSON so that it can be packaged and sent across an API or server; this process is parsing. You can parse a string to JSON using the JSON.parse() method and passing the string as an argument.
Note that parsing string to JSON requires you writing the string in proper JSON syntax; if the syntax is incorrect it will throw an error. The way to convert string to JSON in JavaScript is as follows:
const sampleString = '{"firstName":"Stephen","lastName":"Nabena"}';
const toJSON = JSON.parse(sampleString);
console.log(toJSON)
The JSON.parse() method can also be used to parse a string to other object data types:
// Parsing an array
const animals = '["goat", "cow", "fish"]';
const toString = JSON.parse(animals);
console.log(toString);