JavaScript can encode complex programs. But it can also store data in arrays and objects. With JSON we use JavaScript to store data in an efficient format.
To parse JSON, we can use Node.js—the JSON.parse
method is built for this purpose. It returns an easy-to-use JavaScript object.
Here is an example of the JSON.parse
method on a string
that contains an array. Please notice how the quotes of the "text" string
are used to avoid a parsing error.
JSON.parse
on the text string
. This returns an array of 3 elements—the strings cat, bird and frog.// This is a JSON text string. var text = '["cat", "bird", "frog"]'; // Use JSON.parse to convert string to array. var result = JSON.parse(text); // Print result count. console.log("COUNT: " + result.length); // ... Loop over result. for (var i = 0; i < result.length; i++) { console.log("JSON PARSED ITEM: " + result[i]); }COUNT: 3 JSON PARSED ITEM: cat JSON PARSED ITEM: bird JSON PARSED ITEM: frog
With this method we convert an object model into a string
. In this example we just use a string
array and convert it into a JSON string
.
var array = ["cat", "bird", "frog"]; // Use JSON.stringify to get a string. var result = JSON.stringify(array); console.log("STRINGIFY: " + result);STRINGIFY: ["cat","bird","frog"]
JSON is an efficient and well-supported format for data. Node has excellent support for JSON in the JSON.parse
method.