Parse json array to javascript array

How to decode and encode JSON Data in JavaScript

In this session, you will learn how to encode and decode JSON data in JavaScript with the help of an example.

What is JSON

JavaScript Object Notation also knew as JSON. Between server and client relationship JSON is used which is an extremely lightweight data-interchange format for data exchange and easy to parse and quick to generate. JSON is easy to write and understand for both humans and computers which is based on a text format.

Types of JSON

JSON depend upon two basic structures:

Parsing JSON Data in JavaScript

In JavaScript, by using JSON.parse( ) method you can easily data received from the webserver. In JSON string if the given string is not valid, the result you will get is a syntax error. As shown in the example:

By using the JSON.parse( ) method in JavaScript to convert the string into a JavaScript Object and access individual values by using the do notation (.), as shown in the example:

// Store JSON data in a JS variable var json = ''; // Converting JSON-encoded string to JS object var obj = JSON.parse(json); // Accessing individual value from JS object alert(obj.name); // Outputs: Peter alert(obj.age); // Outputs: 22 alert(obj.country); // Outputs: United States

Parsing Nested JSON Data in JavaScript

You can also nested JSON objects and arrays. In JavaScript, JSON objects can contain other JSON objects, nested arrays, arrays, arrays of the JSON object, and so on. In mention below example, you will learn how to extract all the values and parse a nested JSON in JavaScript.

/* Storing multi-line JSON string in a JS variable using the new ES6 template literals */ var json = ` < "book": < "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": < "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11" >> >`; // Converting JSON object to JS object var obj = JSON.parse(json); // Define recursive function to print nested values function printValues(obj) < for(var k in obj) < if(obj[k] instanceof Object) < printValues(obj[k]); >else < document.write(obj[k] + "
"); >; > >; // Printing all the values from the resulting object printValues(obj); document.write("
"); // Printing a single value document.write(obj["book"]["author"] + "
"); // Prints: J. K. Rowling document.write(obj["book"]["characters"][0] + "
"); // Prints: Harry Potter document.write(obj["book"]["price"]["hardcover"]); // Prints: $20.32

Encoding Data as JSON in JavaScript

During an Ajax communication JavaScript object or value from your code sometime need to be transferred to the server. JavaScript provides a method that converts a JavaScript value to a JSON String by using JSON. stringify ( ) as shown in the example:

Читайте также:  Java parameter method return

Stringify a JavaScript Object

Mention below example will show how to convert a JavaScript object to JSON string:

// Sample JS object var obj = ; // Converting JS object to JSON string var json = JSON.stringify(obj); alert(json);

The output result of above example will show as:

Stringify a JavaScript Array

Mention below example will show how to convert a JavaScript array to JSON strings:

// Sample JS array var arr = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; // Converting JS array to JSON string var json = JSON.stringify(arr); alert(json);

The output result of above example will show as:

["Apple","Banana","Mango","Orange","Papaya"]

Источник

JSON .parse()

A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse() , and the data becomes a JavaScript object.

Example — Parsing JSON

Imagine we received this text from a web server:

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

Make sure the text is in JSON format, or else you will get a syntax error.

Use the JavaScript object in your page:

Example

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

Example

Exceptions

Parsing Dates

Date objects are not allowed in JSON.

If you need to include a date, write it as a string.

You can convert it back into a date object later:

Example

Convert a string into a date:

document.getElementById(«demo»).innerHTML = obj.name + «, » + obj.birth;

Or, you can use the second parameter, of the JSON.parse() function, called reviver.

The reviver parameter is a function that checks each property, before returning the value.

Example

Convert a string into a date, using the reviver function:

document.getElementById(«demo»).innerHTML = obj.name + «, » + obj.birth;

Parsing Functions

Functions are not allowed in JSON.

If you need to include a function, write it as a string.

You can convert it back into a function later:

Example

Convert a string into a function:

document.getElementById(«demo»).innerHTML = obj.name + «, » + obj.age();

You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Читайте также:  The this keyword in javascript

Источник

Parse json array to javascript array

Last updated: Jan 7, 2023
Reading time · 3 min

banner

# Parse a JSON Array in JavaScript

Use the JSON.parse() method to parse a JSON array, e.g. JSON.parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

If the provided parameter is not valid JSON, the JSON.parse method throws a SyntaxError exception.

Copied!
const jsonArr = '[, ]'; const arr = JSON.parse(jsonArr); // 👇️ [, ] console.log(arr); console.log(Array.isArray(arr)); // 👉️ true

We used the JSON.parse method to parse a JSON array into its JavaScript equivalent.

The only parameter the JSON.parse method takes is the JSON string that should be parsed.

You can use the Array.isArray method to verify that a value is a native JavaScript array.

Copied!
console.log(Array.isArray([])); // 👉️ true console.log(Array.isArray('')); // 👉️ false

A JSON value will always be of type string.

Copied!
const arr = ['bobby', 'hadz', 'com']; const json = JSON.stringify(arr); console.log(json); // 👉️ ["bobby","hadz","com"] console.log(typeof json); // 👉️ string

If you provide an invalid JSON string to the method, a SyntaxError exception is thrown.

Copied!
const invalidJson = '[]'; // ⛔️ SyntaxError: Expected property name or '>' in JSON at position 2 console.log(JSON.parse(invalidJson));

The JSON array in the example doesn’t have double quotes around the id property, which makes it invalid.

The JSON.parse method attempts to parse the JSON but is unable to do so and throws an exception.

# Using a try/catch statement to handle a potential error

If you need to handle this scenario, you can parse the JSON array inside of a try/catch block to make sure your program doesn’t crash.

Copied!
const jsonArr = '[, ]'; let arr; try arr = JSON.parse(jsonArr); console.log('✅ JSON array parsed successfully'); > catch (err) console.log('⛔️ invalid JSON provided'); // report error > // 👇️ [, ] console.log(arr);

If the provided JSON is invalid and our catch block runs where we can handle the error.

If the JSON is valid, it gets parsed and assigned to the arr variable.

If your JSON is invalid, google for a JSON validator and paste it into the text box.

See what errors your JSON contains and correct them — either on the server or use the String.replace or String.replaceAll() methods to correct them on the client.

# Making sure your JSON array is valid

For example, the following code replaces all single quotes with double quotes to produce a valid JSON array.

Copied!
const invalidJson = "['apple', 'banana']"; const validJson = invalidJson.replaceAll(`'`, `"`); // 👇️ const parsed = JSON.parse(validJson); console.log(parsed);

We used the String.replaceAll() method to replace all occurrences of single quotes with double quotes to make the JSON array valid.

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.

Strings are immutable in JavaScript.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How To Parse A JSON Array In JavaScript

JSON is a lightweight data format used to store data. In JavaScript, we are provided with two methods: JSON.parse() and JSON.stringify() to parse a JSON Array in JavaScript. I will show you how to use these two methods in this article.

Parse a JSON Array in JavaScript

Using the JSON.parse() method

The JSON.parse() method in JavaScript is used to parse a string written as JSON and convert it to a JavaScript object. To parse a JSON array in JavaScript, we can simply give the JSON.parse() a JSON array then the method will return a JavaScript array instead of a JavaScript object.

jsonArray: Parsed JSON array.

For example:

Let’s parse the below JSON array into a JavaScript array.

var jsonFruit = '<"Fruit":[' + '<"name": "Apple", "quantity": "5">,' + ',' + ']>'; // Parse a JSON Array var fruit = JSON.parse(jsonFruit); console.log(fruit);

By using JSON.parse() , we have easily parsed a JSON array and built a JavaScript array from that given array. However, this method only works if the input string is a valid JSON string. In case the string is not valid JSON, it will return a syntax error.

Using the JSON.stringify() method

While the JSON.parse() method parses the JSON string and converts it to JavaScript’s Object, the JSON.stringify() method does the opposite. JSON.stringify() converts the given JavaScript object into a JSON string.

jsArray : The JavaScript array needs to be converted to a JSON string.

For example:

Let’s convert the below JavaScript array into a JSON string.

var fruit = [< Fruite: [ < name: "Apple", quantity: "5" >, < name: "Apricot", quantity: "10" >, < name: "Banana", quantity: "15" >] >]; // Convert JavaScript array to JSON string var jsonFruit = JSON.stringify(fruit); console.log(jsonFruit);

The JSON.stringify() is a classic method in JavaScript to convert Objects to JSON. The JSON.stringify() method is used in conjunction with the JSON.parse() method, which is intended to help us efficiently convert between JavaScript arrays and JSON arrays. This is also a way to help us copy an Object without affecting the old Object.

Summary

This article taught you how to parse a JSON Array in JavaScript through the above explanations and examples. Using the JSON.parse() method and the JSON.stringify() method makes it easy to work with JSON in JavaScript, and you can apply these two methods flexibly to achieve your purpose. Hope this article will be helpful to you.

Hi, I’m Mary Ralston. I have experience programming in HTML, javascript, C++,… and I want to share with you my experience. So if you want to know more about the above languages read my articles

Источник

Оцените статью