JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. This tutorial covers how to work with JSON responses in JavaScript.
JavaScript JSON Responses
1. What is JSON?
JSON is a format that represents structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.
{
"name": "John",
"age": 30,
"city": "New York"
}
In this example, we have a JSON object with three properties: name, age, and city.
2. Fetching JSON Data
You can fetch JSON data from a server using the Fetch API. Here’s an example of making a GET request to retrieve JSON data.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error('Error fetching data:', error));
This code fetches data from the specified URL, converts the response to JSON, and logs it to the console.
3. Parsing JSON
If you have a JSON string, you can parse it into a JavaScript object using JSON.parse()
.
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj.name); // Output: John
In this example, we parse the JSON string and access the name
property of the resulting object.
4. Stringifying Objects
To convert a JavaScript object into a JSON string, use JSON.stringify()
.
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person);
console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}
This converts the person
object into a JSON string.
5. Example: Working with a JSON API
Here’s a complete example that fetches data from a public API and displays it on the web page:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {
const userList = document.getElementById('user-list');
data.forEach(user => {
const listItem = document.createElement('li');
listItem.textContent = user.name;
userList.appendChild(listItem);
});
})
.catch(error => console.error('Error fetching data:', error));
In this example, we fetch a list of users from a public API and dynamically create list items to display their names.
HTML:
<ul id="user-list"></ul>
6. Conclusion
Working with JSON in JavaScript is essential for modern web development, especially when dealing with APIs. Understanding how to fetch, parse, and manipulate JSON data will help you build more dynamic and interactive web applications.