Home
Map
JSON.parse ExamplesConvert a JSON string to an array of objects with JSON.parse. Also use JSON.stringify.
Node.js
This page was last reviewed on Dec 13, 2023.
JSON. 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.
Array
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.
An example. 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.
Start We invoke 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
Stringify. 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"]
A summary. JSON is an efficient and well-supported format for data. Node has excellent support for JSON in the JSON.parse method.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.