JSON is the most common format for sending data between web browsers and servers today. It is simpler and lighter than XML.
Introduction to JSON
JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging data, made popular by Douglas Crockford in the early 2000s. It is based on the syntax of JavaScript objects, but it is language-independent: almost every language can read and write it. It is used by web APIs, AJAX responses, configuration files (package.json) and NoSQL databases such as MongoDB. Its media type is application/json and files use the extension .json.
Definition: JSON. JavaScript Object Notation, a lightweight text format for structured data made of key-value pairs and ordered lists, used for exchanging data between applications.
Keys and Values
JSON data is written as key-value pairs. A key is always a string in double quotes, followed by a colon and a value: "name": "Asha". Pairs are separated by commas. Single quotes, comments and trailing commas are not allowed.
Types of Values
A JSON value can be one of six types: a string ("BCA"), a number (88.5, with no quotes), a boolean (true or false), null, an object (a set of pairs in braces) or an array (a list in brackets). Functions, dates and undefined are not valid JSON values; dates are usually stored as strings.
Objects and Arrays
A JSON object is written in braces: {"regno": "2526BCA001", "name": "Asha", "marks": 88}. A JSON array is an ordered list in brackets: [78, 85, 62]. Objects and arrays can be nested: a class object can hold an array of student objects, each with an array of marks. Values are reached by path: data.students[0].name.
Parsing and Stringifying
In JavaScript, JSON.parse(text) converts JSON text into a JavaScript object (for example, after receiving it from a server), and JSON.stringify(object) converts an object into JSON text (for sending or storing). JSON.stringify(obj, null, 2) adds indentation for readability. With fetch, response.json() parses the JSON automatically. To populate a page, the script parses the JSON and creates DOM elements, such as table rows, for each item.
JSON and XML
JSON is shorter, faster to parse and maps directly to JavaScript objects; XML supports attributes, namespaces, comments and schemas, and suits documents. Most modern web APIs use JSON.
Table 4.6: JSON value types
| Type | Example | Note |
|---|---|---|
| String | "Asha" | Double quotes only |
| Number | 88.5 | No quotes |
| Boolean | true | Lower case |
| Null | null | Empty value |
| Object | {"a": 1} | Key-value pairs in braces |
| Array | [1, 2, 3] | Ordered list in brackets |
Example 4.6: Transforming and populating JSON
Problem: Given JSON text for a class with an array of students, convert it to a JavaScript object, compute each student's average, add a new student, and convert it back to JSON.
Solution:
- JSON.parse turns the text into an object.
- Loop over obj.students and average each marks array.
- push a new student object onto the array.
- JSON.stringify turns the object back into text.
Result: The script prints each student with an average and the updated JSON.
const text = `{"course": "BCA", "students": [
{"name": "Asha", "marks": [78, 92, 85], "hosteller": true},
{"name": "Ravi", "marks": [65, 70, 74], "hosteller": false}]}`;
const data = JSON.parse(text); // text -> object
for (const s of data.students) {
const avg = s.marks.reduce((a, b) => a + b) / s.marks.length;
console.log(`${s.name}: average ${avg.toFixed(1)}`);
}
data.students.push({ name: "Meera", marks: [90, 88, 95],
hosteller: true });
console.log(typeof data, "| students:", data.students.length);
console.log(JSON.stringify(data.students[2])); // object -> text
Output
Asha: average 85.0
Ravi: average 69.7
object | students: 3
{"name":"Meera","marks":[90,88,95],"hosteller":true}
Common mistakes
- Using single quotes for keys or strings, which is invalid JSON.
- Leaving a trailing comma after the last item.
- Forgetting to parse JSON text before using it as an object.
Key takeaways
- JSON is a lightweight, language-independent data format.
- Keys are strings in double quotes; values are string, number, boolean, null, object or array.
- Objects use braces, arrays use brackets, and they can be nested.
- JSON.parse converts text to an object; JSON.stringify does the reverse.
Practice questions
- What does JSON stand for?
- Name the six types of JSON values.
- What does JSON.parse() do?
Answers to the practice questions
- JavaScript Object Notation.
- String, number, boolean, null, object and array.
- It converts JSON text into a JavaScript object.
Sources
- Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit IV
