Menu
CoddyTech

JSON Text and Values

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 11 of 33.

A file holds text. Your program often needs an array instead. JSON is a text format for values such as arrays, objects, numbers and strings. The quotes around the entire value below make it text, even though its contents look like an array.

const text = '[10,20]';
const scores = JSON.parse(text);
console.log(scores[0]); // 10
console.log(scores.length); // 2

JSON.parse reads the text and returns the value it describes. Count the resulting items, not the characters in the text. JSON strings and object keys use double quotes.

challenge icon

Challenge

Easy

For this exercise, Run executes node practice.js. The notes tool returns in Reading a File. The starter treats JSON text as if it were an array.

Parse text into an array. Print its first item and its item count on separate lines. With no arguments, expect Buy milk then 3. Try the argument '["Walk","Read"]': expect Walk then 2.

Try it yourself

const text = process.argv[2] ?? '["Buy milk","Call Ada","Read"]';
console.log(text[0]);
console.log(text.length);

All lessons in Node.js Basics

Practice on your own: Express playground