KandZ – Tuts

We like to help…!

JavaScript 26 🧬 JSON

a - What is JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format
It is easy for humans to read and write and easy for machines to parse and generate.
It's based on two structures:
Objects: An unordered set of name/value pairs.
Arrays: An ordered collection of values.
In JSON, you can use the following data types:
Objects: {} or new Object()
Arrays: [] or new Array()
Strings: "string" or 'string'
Numbers: 123 (can be integers or floating-point numbers)
Booleans: true or false
Null: null
Always handle errors when parsing JSON strings using try-catch blocks.
Avoid serializing large objects if performance is a concern.
Be cautious when parsing JSON data from untrusted sources to avoid security vulnerabilities like XSS or JSON hijacking.

b - JSON with Javascript
JSON.parse() method is used to parse a JSON string and construct the JavaScript value or object described by the string.
const obj = JSON.parse(jsonString); → parses JSON string
JSON.parse() can also take a second argument, a reviver function. This function is called for each member of the object after it has been parsed.
const obj = JSON.parse(jsonString, (key, value) = {} → revive function example
JSON.parse() can throw a SyntaxError if the input string is not valid JSON. It's a good practice to handle these errors using try-catch blocks.
SON.stringify() method converts a JavaScript object or value to a JSON string
const jsonString = JSON.stringify(obj); → converts an object to JSON string
You can pass a second argument to JSON.stringify() to format the output string for readability.
JSON.stringify() can also take a second argument as a replacer function. This function is called for each member of the object before it has been stringified.

Leave a Reply