JSON-to-data conversion in JavaScript
Using the JSON.parse
method,
you can convert JSON to a JavaScript
data structure. Let's look at an example.
Let's say we have a string containing an array in JSON format:
let json = '[1, 2, 3, 4, 5, "a", "b"]';
Let's convert our string to an array:
let arr = JSON.parse(json);
If the string contains invalid JSON, our method will throw an error:
let json = '[1, 2, 3, 4, 5,]'; // invalid JSON
let arr = JSON.parse(json); // throws an error
Given a JSON string containing an array of numbers:
let json = '[1,2,3,4,5]';
Convert this string to a real JavaScript array and find the sum of the numbers of this array.
Given a JSON string containing an object with data:
let json = `{
"data1": [1,2,3],
"data2": [4,5,6],
"data3": [7,8,9]
}`;
Find the sum of numbers from the given data.
Given a JSON string containing usernames:
let json = '["user1","user2","user3","user4","user5"]';
Output these names as
an ul
list.
Given a JSON string, containing an array with employees data:
let json = `[
{
"name": "user1",
"age": 25,
"salary": 1000
},
{
"name": "user2",
"age": 26,
"salary": 2000
},
{
"name": "user3",
"age": 27,
"salary": 3000
}
]`;
Display these employees in the form of an HTML table.