Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSON data format


May 08, 2021 JSON


Table of contents


JSON data format

JSON is short for JavaScript Object Notation and is a lightweight data notation method. The json format, which records data in a key:value manner, is intuitive and simpler than XML, making it popular

Before we introduce the Johnson format, let's look at the XML format. Obviously, XML has received considerable attention (both positive and negative reviews) and is already widely used in Ajax applications:

<request>
  <firstName>Brett</firstName>
  <lastName>McLaughlin</lastName>
  <email>[email protected]</email>
</request>

The data here is the same as you saw earlier, but this time in XML format. I t's no big deal; it's just another data format that allows us to use XML instead of plain text and name/value pairs.

This article discusses another data format, JavaScript Object Notation (JSON). J SON looks familiar and strange. It offers an alternative, and a wider selection is always a good thing.

Add JSON

When using name/value pairs or XML, you actually use JavaScript to take data from your application and convert it into another data format. In these cases, JavaScript is largely used as a data manipulation language to move and manipulate data from Web forms and to convert data into a format suitable for sending to server-side programs.

Sometimes, however, JavaScript is used more than just as a formatted language. I n these cases, objects in the JavaScript language are actually used to represent the data, not just the data from the Web form into the request. I n these cases, it's a bit more of a move to extract data from a JavaScript object and then put it into a name/value pair or XML. This is when JSON:JSON allows you to easily convert JavaScript objects into data that can be sent on request (synchronous or asynchronous).

JSON is not some kind of magic bullet;

Simply put, JSON can convert a set of data represented by a JavaScript object into a string, which can then be easily passed between functions, or passed from a Web client to a server-side program in an asynchronous application. T his string may seem odd (you'll see a few examples later), but JavaScript is easy to interpret, and JSON can represent structures that are more complex than name/value pairs. F or example, you can represent arrays and complex objects, not just simple lists of keys and values. JSON Foundation

Simple JSON example

In its simplest form, a name/value pair can be represented by jSON like this:

{ "firstName": "Brett" }

This example is very basic and actually takes up more space than the equivalent plain text name/value pair:

firstName=Brett

However, when multiple name/value pairs are stringed together, JSON reflects its value. First, you can create a record that contains multiple name/value pairs, such as:

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }

In terms of syntax, this is not a great advantage over name/value pairs, but JSON is easier to use and readable in this case. For example, it explicitly states that all three values are part of the same record;

An array of values

When you need to represent a set of values, JSON not only improves readability, but also reduces complexity. F or example, suppose you want to represent a list of people's names. In XML, many start and end tags are required, and if you use a typical name/value pair (as you saw earlier in this series), you must establish a proprietary data format, or modify the key name to a form such as person1-firstName.

If you use JSON, you only need to group multiple records with braces together:

{ "people": [
  { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
  { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
  { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
]}

It's not hard to understand. I n this example, there is only one variable named people, and the value is an array of three entries, each of which is a record of one person, with a first name, last name, and e-mail address. T he example above shows how to combine records into a single value in parentheses. Of course, you can use the same syntax to represent multiple values (each value contains multiple records):

{ "programmers": [
  { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
  { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
  { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
 ],
"authors": [
  { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
  { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
  { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
 ],
"musicians": [
  { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
  { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
 ]
}

Most notably, you can represent multiple values, each of which in turn contains multiple values. H owever, it should also be noted that the actual name/value pairs in the record can be different between different main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing for changes in the way data is represented in the middle of the JSON structure.

There are no predefined constraints to follow when working with data in JSON format. So, in the same data structure, you can change the way you represent data, and you can even represent the same thing in different ways.

Once you've mastered the JSON format by assigning JSON data to variables, it's easy to use it in JavaScript. J SON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript. Use JSON in JavaScript

For example, you can create a new JavaScript variable and assign a data string in JSON format directly to it:

var people =
  { "programmers": [
    { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
    { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
    { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
   ],
  "authors": [
    { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
    { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
    { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
   ],
  "musicians": [
    { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
    { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
   ]
  }

It's very simple; now people contain the data in the JSON format you saw earlier. However, this is not enough, as the way data is accessed does not seem obvious.

Access the data

Although it doesn't look obvious, the long string above is really just an array; I n fact, you only need to represent array elements with a dot notation. So to access the last name of the first entry in the programmers list, simply use the following code in JavaScript:

people.programmers[0].lastName;

Note that the array index starts at zero. S o, this line of code first accesses the data in the people variable, then moves to an entry called programmers, then moves to the first record, and finally, accesses the value of the lastName key. The result is the string value "McLaughlin."

Here are a few examples of using the same variable.

people.authors[1].genre                       // Value is "fantasy"
people.musicians[3].lastName          // Undefined. This refers to the fourth entry, and there isn't one
people.programmers.[2].firstName      // Value is "Elliotte"

With this syntax, you can work with data in any JSON format without using any additional JavaScript toolkits or APIs.

Modify the JSON data

Just as data can be accessed with dots and parentheses, it can be easily modified in the same way:

people.musicians[1].lastName = "Rachmaninov";

After you convert a string to a JavaScript object, you can modify the data in the variable like this.

Convert back to the string

Of course, if you can't easily convert objects back to the text format mentioned in this article, all data modifications are of little value. In JavaScript, this transformation is also simple:

String newJSONtext = people.toJSONString();

That's it! You now get a text string that you can use anywhere, for example, as a request string in an Ajax application.

What's more, you can convert any JavaScript object to JSON text. Y ou can't just handle variables that were originally assigned with the JSON string. In order to convert an object named myObject, simply execute the same form of command:

String myObjectInJSON = myObject.toJSONString();

This is the biggest difference between JSON and the other data formats discussed in this series. I f you use JSON, you can get formatted data by calling a simple function, which you can use directly. F or other data formats, you need to convert between raw and formatted data. Even using an API like Document Object Model, which provides functions to convert your data structure to text, you need to learn the API and use API objects instead of native JavaScript objects and syntax.

The final conclusion is that JSON is almost certainly a good choice if you want to work with a large number of JavaScript objects, so that you can easily convert the data to a format that can be sent to server-side programs in a request.