What is JSON and its common operations?
What is JSON?
JSON is a text-based format that represents data as key-value pairs or arrays. It is a lightweight alternative to XML and is more human-readable than other formats like CSV (Comma Separated Values). JSON data is typically represented as a collection of name-value pairs, where each pair consists of a string key and a value.
Example of a Simple JSON Object
{
"name": "John Doe",
"age": 30,
" occupation": "Software Developer"
}
Parsing JSON Strings
We can parse a JSON string into a JavaScript object using JSON.parse()
.
const jsonString = '{"name":"John Doe","age":30}';
const person = JSON.parse(jsonString);
console.log(person);
// Output: { name: "John Doe", age: 30 }
Stringifying JSON Objects
We can convert a JavaScript object to a JSON string using JSON.stringify()
.
const person = {
name: 'Jane Doe',
age: 25
};
const jsonString = JSON.stringify(person);
console.log(jsonString); // '{"name":"Jane Doe","age":25}'