![]() |
VOOZH | about |
JSON is a text format for representing structured data, typically in the form of key-value pairs. It primarily sends data between a server and a client, especially in web APIs.
JSON object
Working with JSON in JavaScript involves converting JSON data into JavaScript objects (parsing) and vice versa (stringifying).
JSON parsing is the process of converting a JSON string into a native JavaScript object. JavaScript provides the JSON.parse() method for this.
Ravi
Handling Exceptions when Parsing JSON
JSON parsing can fail if the string is not valid JSON. To prevent your application from crashing, use a try...catch block to handle errors.
In this example, the missing bracket causes an error. The catch block helps you handle such issues gracefully.
Once you've parsed JSON and turned it into a JavaScript object, you may want to send it back as a JSON string. This is done using JSON.stringify().
{"name":"Ravi","age":25,"profession":"Web Developer"}
This converts the user object into a string that can be sent over a network or saved in a file.
Once you've parsed a JSON string into a JavaScript object, you can easily modify its properties or add new ones.
{"name":"Ravi","age":25,"profession":"Web Developer"}
Here, we add a new property (profession) to the parsed JSON object and convert it back to a JSON string using JSON.stringify().
You may often need to filter or transform data contained in JSON objects or arrays. JavaScript array methods like filter(), map(), and reduce() are perfect for this.
Filtering JSON Data
Suppose you have an array of user objects, and you want to filter users who are older than 30.
In this example, the filter() method is used to create a new array that only includes users older than 30.
Serialization is the process of converting a JavaScript object into a JSON string. This is commonly done when sending data from the client to the server.
{"name":"Simran","age":29}
This makes the data ready to be transmitted as JSON over HTTP requests or saved in a storage system.
JSON.stringify() allows you to specify which properties to include or exclude from the JSON string by using a replacer function.
{"name":"Jatin","age":32}
In this example, the password field is excluded from the final JSON string.
JSON is the standard format for data exchange with web APIs. JavaScript’s fetch() API allows you to send and receive JSON data easily.
Fetching JSON from an API:
This fetches data from a sample API and logs it to the console.
Sending JSON to an API
In this example, we send JSON data to an API using the POST method.
By following the examples above and integrating JSON operations into your projects, you’ll become proficient in handling JSON in JavaScript.
Apart from that you can follow our articles and Tutorial to Master JSON in Javacript.