JSON basics
Computer Science · JavaScript
Question 1 of 10
0What does this JavaScript code log? const data = JSON.stringify({ name: "loop", n: 114 }); console.log(data.length);
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
JSON basics explained
JSON, short for JavaScript Object Notation, is a plain text format for structured data. It is used to send data between a server and a browser or to store settings in a file, and JavaScript has built-in functions to convert to and from it.
JSON can represent objects, arrays, strings, numbers, true, false and null. Keys and strings must use double quotes. JSON does not allow comments, trailing commas, undefined or functions, so a valid JavaScript object literal is not always valid JSON.
const text = JSON.stringify({ name: "Ada", scores: [9, 7] });
console.log(text);
const back = JSON.parse(text);
console.log(back.scores[0]);
JSON.stringify converts a value to a JSON string and skips properties whose values are undefined or functions. JSON.parse converts text back into values and throws a SyntaxError for invalid input, so parsing external data should be wrapped in try and catch.
Worked example
The object with name "Ada" and scores [9, 7] becomes the 29-character string {"name":"Ada","scores":[9,7]}. JSON.parse turns that text back into an object, and its scores[0] is 9. The output is the text, then 9.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this JavaScript code log?
const data = JSON.stringify({ name: "hi", n: 159 }); console.log(data.length);
Medium
What does this JavaScript code log?
const data = JSON.parse('{"items":[{"v":2},{"v":8},{"v":12}]}'); console.log(data.items[2].v * 8);
Hard
What does this JavaScript code log?
const data = { a: 48, b: undefined, c: NaN, d: () => 1, e: [undefined, 46] }; console.log(JSON.stringify(data).length);