What is JSON?
JSON (JavaScript Object Notation) is a lightweight text format for storing structured data in a human-readable format. Compared to XML, JSON data takes up less space, is easier for humans to read, and for computers to process. JSON is frequently used to transfer data over the network in client/server and server/server communications. JSON itself has no methods and does not support comments; it's just a data storage format. JSON format came from JavaScript, but it is now actively used in almost all programming languages, including PHP, Python, Java, C++, C#, Go, and most of them, like Python, has built-in modules for working with JSON data.
How to decode JSON string in JavaScript?
The JSON.parse(string, reviver) method in JavaScript is intended for decoding (parsing) strings in JSON format. The JSON.parse() method returns an object, array, or elemental value resulting from parsing the passed JSON string. Note that the JSON object uses only double quotes (no single quotes or backticks). Also, JSON does not support comments, which makes it invalid. There is another JSON5 format that supports unquoted keys, comments, etc. But this is a standalone library, not a language specification. Plain JSON is strict because it makes it easy to implement robust and fast encoding and decoding algorithms.
Where:
- string: a string that contains data in JSON format
- function (optional): a function that converts the parsed value before returning it from the method. The function will be called for each element while parsing the string
How to convert values when parsing JSON?
JSON.parse() can take a function as its second parameter. A function can convert object values before they are returned.
How to convert a JavaScript object to a JSON string?
To convert JavaScript objects or arrays to a JSON string, you can use the JSON.stringify() method: