JSON Example

JSON Tutorial — Learn How to Use JSON with JavaScript

Last updated: 18 May 2020 In this tutorial, we’re going to learn about JSON. We will cover JSON structure, different data types and how to use JSON inside JavaScript. JSON is one of the most important concepts that you can learn as a programmer or as a QA. Throughout your programming career you’re going to use JSON all the time whether it’s creating an API, consuming an API, or creating config files for your application.

What is JSON

JSON which stands for JavaScript object notation, is simply a data representation format very similar to XML or YAML. It’s used widely across the internet for almost every single API that you will access, as well as for config files and things such as games and text editors. An example of a JSON:

Why Use JSON

We use JSON because it’s extremely lightweight to send back and forth in http requests and responses due to the small file size. It’s easy to read compared to something like XML since it’s much cleaner and there’s not as many opening and closing tags to worry about. JSON also integrates very nicely with JavaScript since JSON is just a subset of JavaScript, which means anything you write in a JSON is valid JavaScript. Almost every single major language has some form of library or built-in functionality to parse JSON strings into objects or classes in that language. This makes working with JSON data extremely easy inside of a programming language.

Читайте также:  Building gdb with python

JSON Data Types

  • strings
  • numbers numbers can be in any format whether they’re decimal numbers whole numbers negative numbers even scientific notation numbers
  • booleans which can be either true or false
  • null which essentially stands for nothing
  • Arrays which can be a list of any of the types above
  • Objects an object is the most complex but most used type within json as it allows you to represent data that are key value pairs

JSON Example

Let’s dive into an example of how to use json inside of a file.

The first thing that you need to do is to create a file with the .json extension at the end of it.

We’re going to create a user.json file with a user object represented as JSON.

To create an object we need to use opening and closing curly braces <> and then inside of that we’ll put all of the key value pairs that make up our object.

Every single property inside the JSON is a key value pair. The key must be surrounded by double «» quotes followed by a colon : and then the value for that key.

If we have multiple key value pairs, we need commas , separating every single one of our key value pairs, similar to how we would create an array in a normal programming language.

Example JSON File

In the above example, we have a file called user.json . Inside the file we have different data types.

The keys are always surrounded by double quotes. For the values, only the string type is surrounded by double quotes.

  • name is string
  • age is integer
  • isProgrammer is boolean
  • hobbies is an Array
  • friends is an Array of Objects

How to Use JSON String Inside JavaScript

Let’s assume we have a JSON file called companies.json which is an array of company objects:

In the above example, we have two company objects inside a JSON array.

Now let’s see how we can use the above JSON inside a JavaScript.

In most scenarios, we get a JSON as a string rather than a JSON object. To emulate this, we represent the above JSON as a string inside the JavaScript.

         

When we inspect the console log in Chrome Developer Tools, the output is similar to what’s shown below:

JSON javascript example

Then we can parse the above JSON by specifying what we want to extract. For example, if we wanted to get the name of the first company in the array we would use:

console.log(JSON.parse( companies[0].name )) Output: Big corporate 

Likewise, to get the rating of the second company we would use:

console.log(JSON.parse( companies[1].rating )) Output: 4.3 

How to Convert JavaScript Object to JSON

Now suppose we have a JavaScript object like the one shown below:

     var person =  

To convert the person JavaScript object to JSON we use stringify method:

jsonPerson = JSON.stringify(person); 

The output is a valid JSON:

Note: console.log(jsonPerson.name) prints undefined. To get the value, we must convert the JSON back to JavaScript object.

To make the above work, we need to convert the JSON back to JavaScript object.

How to Convert JSON Object to JavaScript

To convert the above JSON object back to JavaScript, we use the parse method:

jsPerson = JSON.parse(jsonPerson) 

Complete Example

         

Summary

  • JSON stands for JavaScript Object Notation
  • Lightweight data-interchange format
  • Based on a subset of JavaScript
  • Easy to read and write
  • Language independent
  • Can be parsed in most modern programming languages
  • Number: No difference between integer and float
  • String: String of Unicode characters. Use double quotes
  • Boolean: True or false
  • Array: Ordered list of 0 or more values in []
  • Object: Unordered collection of key/value pairs
  • Null: Empty value

JSON Syntax Rules:

  • Uses key/value pairs — e.g.
  • Uses double quotes around KEY
  • Must use the specified data types
  • File type is .json
  • MIME type is “Application/json”

I hope you found this JSON tutorial with Javascript useful. You can now write simple and complex JSON files and interact with JSON strings inside JavaScript.

Источник

JavaScript JSON

JSON is often used when data is sent from a server to a web page.

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data interchange format
  • JSON is language independent *
  • JSON is «self-describing» and easy to understand

* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

JSON Example

This JSON syntax defines an employees object: an array of 3 employee records (objects):

JSON Example

The JSON Format Evaluates to JavaScript Objects

The JSON format is syntactically identical to the code for creating JavaScript objects.

Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data — A Name and a Value

JSON data is written as name/value pairs, just like JavaScript object properties.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

JSON names require double quotes. JavaScript names do not.

JSON Objects

JSON objects are written inside curly braces.

Just like in JavaScript, objects can contain multiple name/value pairs:

JSON Arrays

JSON arrays are written inside square brackets.

Just like in JavaScript, an array can contain objects:

In the example above, the object «employees» is an array. It contains three objects.

Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in a web page.

For simplicity, this can be demonstrated using a string as input.

First, create a JavaScript string containing JSON syntax:

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:

Finally, use the new JavaScript object in your page:

Example

document.getElementById(«demo»).innerHTML =
obj.employees[1].firstName + » » + obj.employees[1].lastName;

You can read more about JSON in our JSON tutorial.

Источник

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