Using Javascript to Read Date From a Json File

JSON for Beginners – JavaScript Object Notation Explained in Plain English

Many software applications demand to commutation data between a client and server.

For a long time, XML was the preferred data format when it came to information commutation between the two points. And so in early on 2000, JSON was introduced equally an alternating information format for information exchange.

In this article, you volition learn all virtually JSON. Yous'll understand what it is, how to apply information technology, and nosotros'll clarify a few misconceptions. So, without any farther delay, let'southward become to know JSON.

What is JSON?

JSON (JavaSouthcript Object Notation) is a text-based data exchange format. It is a collection of central-value pairs where the key must be a string type, and the value tin be of any of the following types:

  • Number
  • String
  • Boolean
  • Array
  • Object
  • null

A couple of important rules to note:

  • In the JSON data format, the keys must be enclosed in double quotes.
  • The key and value must be separated by a colon (:) symbol.
  • At that place can be multiple key-value pairs. Two key-value pairs must be separated by a comma (,) symbol.
  • No comments (// or /* */) are allowed in JSON data. (But you can get around that, if you're curious.)

Hither is how some simple JSON data looks:

                  {     "proper noun": "Alex C",     "age": 2,     "city": "Houston" }                
Simple JSON Data

Valid JSON data can exist in ii different formats:

  • A collection of primal-value pairs enclosed by a pair of curly braces {...}. Y'all saw this as an instance above.
  • A drove of an ordered list of key-value pairs separated by comma (,) and enclosed by a pair of square brackets [...]. See the example below:
                  [ 	{         "name": "Alex C",         "age": 2,         "city": "Houston" 	},     {         "proper name": "John G",         "age": twoscore,         "metropolis": "Washington" 	},     {         "name": "Bala T",         "historic period": 22,         "city": "Bangalore" 	} ]                
JSON Information with a Drove of Ordered Records

Suppose you are coming from a JavaScript developer background. In that case, you may feel like the JSON format and JavaScript objects (and array of objects) are very similar. Only they are non. We will see the differences in detail soon.

The construction of the JSON format was derived from the JavaScript object syntax. That'south the only relationship between the JSON data format and JavaScript objects.

JSON is a programming language-independent format. We can use the JSON information format in Python, Java, PHP, and many other programming languages.

JSON Data Format Examples

Y'all can salvage JSON data in a file with the extension of .json. Let's create an employee.json file with attributes (represented by keys and values) of an employee.

                  { 	"proper name": "Aleix Melon", 	"id": "E00245", 	"role": ["Dev", "DBA"], 	"age": 23, 	"doj": "11-12-2019", 	"married": faux, 	"accost": { 		"street": "32, Laham St.", 		"metropolis": "Innsbruck", 		"country": "Republic of austria" 	}, 	"referred-by": "E0012" }                
Employee Data in JSON Format

The above JSON data shows the attributes of an employee. The attributes are:

  • proper name: the proper name of the employee. The value is of String type. So, information technology is enclosed with double quotes.
  • id: a unique identifier of an employee. It is a String type over again.
  • role: the roles an employee plays in the system. In that location could be multiple roles played by an employee. So Assortment is the preferred data type.
  • historic period: the current historic period of the employee. It is a Number.
  • doj: the date the employee joined the company. Every bit it is a date, it must exist enclosed within double-quotes and treated like a String.
  • married: is the employee married? If then, true or false. So the value is of Boolean type.
  • address: the accost of the employee. An address can have multiple parts like street, city, land, zip, and many more. And so, nosotros tin can treat the address value as an Object representation (with cardinal-value pairs).
  • referred-by: the id of an employee who referred this employee in the organization. If this employee joined using a referral, this attribute would have value. Otherwise, it will have zilch as a value.

Now let'southward create a collection of employees as JSON information. To do that, we need to keep multiple employee records within the square brackets [...].

                  [ 	{         "name": "Aleix Melon",         "id": "E00245",         "function": ["Dev", "DBA"],         "age": 23,         "doj": "11-12-2019",         "married": false,         "accost": {             "street": "32, Laham St.",             "city": "Innsbruck",             "country": "Austria"             },         "referred-by": "E0012" 	},     {         "name": "Bob Washington",         "id": "E01245",         "role": ["HR"],         "age": 43,         "doj": "ten-06-2010",         "married": true,         "address": {             "street": "45, Abraham Lane.",             "city": "Washington",             "state": "U.s.a."             },         "referred-past": naught 	} ]                
An Array of Employee Information in JSON Format

Did you lot notice the referred-past aspect value for the 2nd employee, Bob Washington? It is nix. It means he was not referred by any of the employees.

How to Employ JSON Data equally a Cord Value

We have seen how to format JSON information within a JSON file. Alternatively, we tin can apply JSON data equally a string value and assign it to a variable. Equally JSON is a text-based format, it is possible to handle equally a cord in about programming languages.

Let's take an example to sympathise how we can practise information technology in JavaScript. Yous can enclose the unabridged JSON data as a string inside a single quote '...'.

                  const user = '{"name": "Alex C", "historic period": 2, "city": "Houston"}';                
JSON Data as a Cord Value - Using quotes

If y'all want to keep the JSON formatting intact, you lot can create the JSON data with the help of template literals.

                  const user = `{     "proper noun": "Alex C",     "age": two,     "metropolis": "Houston" }`;                                  
JSON Data equally a String Value - Using Template Literals

It is as well useful when y'all desire to build JSON data using dynamic values.

                  const age = 2;  const user = `{     "name": "Alex C",     "historic period": ${age},     "metropolis": "Houston" }`;  panel.log(user);  // Output {     "name": "Alex C",     "historic period": 2,     "city": "Houston" }                
Build JSON Data using Dynamic Value

JavaScript Objects and JSON are NOT the Same

The JSON data format is derived from the JavaScript object structure. But the similarity ends at that place.

Objects in JavaScript:

  • Tin take methods, and JSON can't.
  • The keys can be without quotes.
  • Comments are allowed.
  • Are JavaScript's own entity.

Here'southward a Twitter thread that explains the differences with a few examples.

A Tweet Comparing JavaScript Object and JSON. Liked it? Please Give a FOLLOW.

How to Catechumen JSON to a JavaScript Object, and vice-versa

JavaScript has two congenital-in methods to convert JSON data into a JavaScript object and vice-versa.

How to Convert JSON Data to a JavaScript Object

To convert JSON data into a JavaScript object, use the JSON.parse() method. It parses a valid JSON string into a JavaScript object.

                                      const userJSONData = `{     "name": "Alex C",     "age": 2,     "city": "Houston" }`;  const userObj = JSON.parse(userJSONData); console.log(userObj);                
Json Data to JavaScript Object

Output:

first
The output

How to Convert a JavaScript Object to JSON Data

To convert a JavaScript object into JSON information, use the JSON.stringify() method.

                  const userObj = {     name: 'Alex C',      age: 2,      urban center: 'Houston' }  const userJSONData = JSON.stringify(userObj); console.log(userJSONData);                
JavaScript Object to JSON information

Output:

second
The output


Did you lot find the JSON term nosotros used to invoke the parse() and stringify() methods above? That's a congenital-in JavaScript object named JSON (could have been named JSONUtil equally well) but information technology's not related to the JSON data format we've discussed so far. So, delight don't get confused.

How to Handle JSON Errors like "Unexpected token u in JSON at position 1"?

While handling JSON, it is very normal to become an mistake like this while parsing the JSON information into a JavaScript object:

image-127
JSON Syntax Mistake

Whenever you meet this error, please question the validity of your JSON data format. You probably fabricated a trivial error and that is causing it. You lot can validate the format of your JSON data using a JSON Linter.

Before Nosotros Cease...

I promise you institute the article insightful and informative. My DMs are open up on Twitter if yous want to hash out farther.

Recently I have published a few helpful tips for beginners to web evolution. You lot may desire to have a await:

v tips for beginners to spider web evolution

Are you a beginner in web evolution? I have a few tips for you to sustain and progress your web development goals. Please read on.

r?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1637560099463%2FV30AycjQN

GreenRoots Blog

Let's connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well:

  • Follow me on Twitter
  • Subscribe to my YouTube Channel
  • Side projects on GitHub


Larn to code for free. freeCodeCamp's open source curriculum has helped more than xl,000 people get jobs as developers. Go started

rodriguezrevey1974.blogspot.com

Source: https://www.freecodecamp.org/news/what-is-json-a-json-file-example/

0 Response to "Using Javascript to Read Date From a Json File"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel