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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).