How-To Geek

What is json and how do you use it.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

9 Apple HomeKit Features You Need to Try

5 reasons why i stopped using ubuntu, 6 ways to get the most out of your quest vr headset, quick links, json basics, a basic json example, json data types, semantics and validation, designating json content, working with json, json limitations, json alternatives.

JSON (JavaScript Object Notation) is a standardized format for representing structured data. Although JSON grew out of the JavaScript programming language, it's now an ubiquitous method of data exchange between systems. Most modern-day APIs accept JSON requests and issue JSON responses so it's useful to have a good working knowledge of the format and its features.

In this article, we'll explain what JSON is, how it expresses different data types, and the ways you can produce and consume it in popular programming languages. We'll also cover some of JSON's limitations and the alternatives that have emerged.

JSON was originally devised by Douglas Crockford as a stateless format for communicating data between browsers and servers. Back in the early 2000s, websites were beginning to asynchronously fetch extra data from their server, after the initial page load. As a text-based format derived from JavaScript, JSON made it simpler to fetch and consume data within these applications. The specification was eventually standardized as ECMA-404 in 2013 .

JSON is always transmitted as a string. These strings can be decoded into a range of basic data types, including numbers, booleans, arrays, and objects. This means object hierarchies and relationships can be preserved during transmission, then reassembled on the receiving end in a way that's appropriate for the programming environment.

This is a JSON representation of a blog post:

"id": 1001,

"title": "What is JSON?",

"author": {

"name": "James Walker"

"tags": ["api", "json", "programming"],

"published": false,

"publishedTimestamp": null

This example demonstrates all the JSON data types. It also illustrates the concision of JSON-formatted data, one of the characteristics that's made it so appealing for use in APIs. In addition, JSON is relatively easy to read as-is, unlike more verbose formats such as XML .

Six types of data can be natively represented in JSON:

  • Strings - Strings are written between double quotation marks; characters may be escaped using backslashes.
  • Numbers - Numbers are written as digits without quotation marks. You can include a fractional component to denote a float. Most JSON parsing implementations assume an integer when there's no decimal point present.
  • Booleans - The literal values true and false are supported.
  • Null - The null literal value can be used to signify an empty or omitted value.
  • Arrays - An array is a simple list denoted by square brackets. Each element in the list is separated by a comma. Arrays can contain any number of items and they can use all the supported data types.
  • Objects - Objects are created by curly brackets. They're a collection of key-value pairs where the keys are strings, wrapped in double quotation marks. Each key has a value that can take any of the available data types. You can nest objects to create cascading hierarchies. A comma must follow each value, signifying the end of that key-value pair.

JSON parsers automatically convert these data types into structures appropriate to their language. You don't need to manually cast

to an integer, for example. Parsing the entire JSON string is sufficient to map values back to their original data format.

JSON has certain rules that need to be respected when you encode your data. Strings that don't adhere to the syntax won't be parseable by consumers.

It's particularly important to pay attention to quotation marks around strings and object keys. You must also ensure a comma's used after each entry in an object or array. JSON doesn't allow a trailing comma after the last entry though - unintentionally including one is a common cause of validation errors. Most text editors will highlight syntax problems for you, helping to uncover mistakes.

Despite these common trip points, JSON is one of the easiest data formats to write by hand. Most people find the syntax quick and convenient once they gain familiarity with it. Overall JSON tends to be less error-prone than XML, where mismatched opening and closing tags, invalid schema declarations, and character encoding problems often cause issues.

extension is normally used when JSON is saved to a file. JSON content has the standardized MIME type

is sometimes used for compatibility reasons. Nowadays you should rely on

HTTP headers.

Most APIs that use JSON will encapsulate everything in a top-level object:

"error": 1000

This isn't required though - a literal type is valid as the top-level node in a file, so the following examples are all valid JSON too:

They'll decode to their respective scalars in your programming language.

Most programming languages have built-in JSON support. Here's how to interact with JSON data in a few popular environments.

In JavaScript the

methods are used to encode and decode JSON strings:

const post = {

title: "What Is JSON?",

name: "James Walker"

const encodedJson = JSON.stringify(post);

// {"id": 1001, "title": "What Is JSON?", ...}

console.log(encodedJson);

const decodedJson = JSON.parse(encodedJson);

// James Walker

console.log(decodedJson.author.name);

The equivalent functions in PHP are

"id" => 1001,

"title" => "What Is JSON?",

"author" => [

"id" => 1,

"name" => "James Walker"

$encodedJson = json_encode($post);

echo $encodedJson;

$decodedJson = json_decode($encodedJson, true);

echo $decodedJson["author"]["name"];

Python provides

to serialize and deserialize respectively:

import json

"title": "What Is JSON?",

encodedJson = json.dumps(post)

# {"id": 1001, "title": "What Is JSON?", ...}

print(encodedJson)

decodedJson = json.loads(encodedJson)

# James Walker

print(decodedJson["author"]["name"])

Ruby offers

require "json"

"author" => {

encodedJson = JSON.generate(post)

puts encodedJson

decodedJson = JSON.parse(encodedJson)

puts decodedJson["author"]["name"]

JSON is a lightweight format that's focused on conveying the values within your data structure. This makes it quick to parse and easy to work with but means there are drawbacks that can cause frustration. Here are some of the biggest problems.

No Comments

JSON data can't include comments. The lack of annotations reduces clarity and forces you to put documentation elsewhere. This can make JSON unsuitable for situations such as config files, where modifications are infrequent and the purposes of fields could be unclear.

JSON doesn't let you define a schema for your data. There's no way to enforce that

is a required integer field, for example. This can lead to unintentionally malformed data structures.

No References

Fields can't reference other values in the data structure. This often causes repetition that increases filesize. Returning to the blog post example from earlier, you could have a list of blog posts as follows:

"id": 1002,

"title": "What is SaaS?",

Both posts have the same author but the information associated with that object has had to be duplicated. In an ideal world, JSON parser implementations would be able to produce the structure shown above from input similar to the following:

"author": "{{ .authors.james }}"

"authors": {

This is not currently possible with standard JSON.

No Advanced Data Types

The six supported data types omit many common kinds of value. JSON can't natively store dates, times, or geolocation points, so you need to decide on your own format for this information.

This causes inconvenient discrepancies and edge cases. If your application handles timestamps as strings, like

, but an external API presents time as seconds past the Unix epoch -

- you'll need to remember when to use each of the formats.

YAML is the leading JSON alternative. It's a superset of the format that has a more human-readable presentation, custom data types, and support for references. It's intended to address most of the usability challenges associated with JSON.

YAML has seen wide adoption for config files and within DevOps , IaC , and observability tools. It's less frequently used as a data exchange format for APIs. YAML's relative complexity means it's less approachable to newcomers. Small syntax errors can cause confusing parsing failures.

Protocol buffers (protobufs) are another emerging JSON contender designed to serialize structured data. Protobufs have data type declarations, required fields, and support for most major programming languages. The system is gaining popularity as a more efficient way of transmitting data over networks.

JSON is a text-based data representation format that can encode six different data types. JSON has become a staple of the software development ecosystem; it's supported by all major programming languages and has become the default choice for most REST APIs developed over the past couple of decade.

While JSON's simplicity is part of its popularity, it also imposes limitations on what you can achieve with the format. The lack of support for schemas, comments, object references, and custom data types means some applications will find they outgrow what's possible with JSON. Younger alternatives such as YAML and Protobuf have helped to address these challenges, while XML remains a contender for applications that want to define a data schema and don't mind the verbosity.

  • Programming

JSON for Beginners – JavaScript Object Notation Explained in Plain English

Tapas Adhikary

Many software applications need to exchange data between a client and server.

For a long time, XML was the preferred data format when it came to information exchange between the two points. Then in early 2000, JSON was introduced as an alternate data format for information exchange.

In this article, you will learn all about JSON. You'll understand what it is, how to use it, and we'll clarify a few misconceptions. So, without any further delay, let's get to know JSON.

What is JSON?

JSON ( J ava S cript O bject N otation) is a text-based data exchange format. It is a collection of key-value pairs where the key must be a string type, and the value can be of any of the following types:

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.
  • There 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.)

Here is how some simple JSON data looks:

Valid JSON data can be in two different formats:

  • A collection of key-value pairs enclosed by a pair of curly braces {...} . You saw this as an example above.
  • A collection of an ordered list of key-value pairs separated by comma (,) and enclosed by a pair of square brackets [...] . See the example below:

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. But they are not. We will see the differences in detail soon.

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

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

JSON Data Format Examples

You can save 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.

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

  • name : the name of the employee. The value is of String type. So, it is enclosed with double quotes.
  • id : a unique identifier of an employee. It is a String type again.
  • role : the roles an employee plays in the organization. There could be multiple roles played by an employee. So Array is the preferred data type.
  • age : the current age of the employee. It is a Number .
  • doj : the date the employee joined the company. As it is a date, it must be enclosed within double-quotes and treated like a String .
  • married : is the employee married? If so, true or false. So the value is of Boolean type.
  • address : the address of the employee. An address can have multiple parts like street, city, country, zip, and many more. So, we can treat the address value as an Object representation (with key-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 null as a value.

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

Did you notice the referred-by attribute value for the second employee, Bob Washington? It is null . It means he was not referred by any of the employees.

How to Use JSON Data as a String Value

We have seen how to format JSON data inside a JSON file. Alternatively, we can use JSON data as a string value and assign it to a variable. As JSON is a text-based format, it is possible to handle as a string in most programming languages.

Let's take an example to understand how we can do it in JavaScript. You can enclose the entire JSON data as a string within a single quote '...' .

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

It is also useful when you want to build JSON data using dynamic values.

JavaScript Objects and JSON are NOT the Same

The JSON data format is derived from the JavaScript object structure. But the similarity ends there.

Objects in JavaScript:

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

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

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

JavaScript has two built-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.

Image

How to Convert a JavaScript Object to JSON Data

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

Image

Did you notice the JSON term we used to invoke the parse() and stringify() methods above? That's a built-in JavaScript object named JSON (could have been named JSONUtil as well) but it's not related to the JSON data format we've discussed so far. So, please 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 get an error like this while parsing the JSON data into a JavaScript object:

Image

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

Before We End...

I hope you found the article insightful and informative. My DMs are open on Twitter if you want to discuss further.

Recently I have published a few helpful tips for beginners to web development. You may want to have a look:

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

Demand-Stack Developer. I teach on YouTube youtube.com/tapasadhikary how to level up your tech career. An Open Source Enthusiast, Writer.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Working with JSON

  • Overview: Introducing JavaScript objects

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.

Prerequisites: A basic understanding of HTML and CSS, familiarity with JavaScript basics (see and ) and OOJS basics (see ).
Objective: To understand how to work with data stored in JSON, and create your own JSON strings.

No, really, what is JSON?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford . Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.

JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two.

Note: Converting a string to a native object is called deserialization , while converting a native object to a string so it can be transmitted across the network is called serialization .

A JSON string can be stored in its own file, which is basically just a text file with an extension of .json , and a MIME type of application/json .

JSON structure

As described above, JSON is a string whose format very much resembles JavaScript object literal format. You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals. This allows you to construct a data hierarchy, like so:

If we loaded this string into a JavaScript program and parsed it into a variable called superHeroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article. For example:

To access data further down the hierarchy, you have to chain the required property names and array indexes together. For example, to access the third superpower of the second hero listed in the members list, you'd do this:

  • First, we have the variable name — superHeroes .
  • Inside that, we want to access the members property, so we use ["members"] .
  • members contains an array populated by objects. We want to access the second object inside the array, so we use [1] .
  • Inside this object, we want to access the powers property, so we use ["powers"] .
  • Inside the powers property is an array containing the selected hero's superpowers. We want the third one, so we use [2] .

Note: We've made the JSON seen above available inside a variable in our JSONTest.html example (see the source code ). Try loading this up and then accessing data inside the variable via your browser's JavaScript console.

Arrays as JSON

Above we mentioned that JSON text basically looks like a JavaScript object inside a string. We can also convert arrays to/from JSON. Below is also valid JSON, for example:

The above is perfectly valid JSON. You'd just have to access array items (in its parsed version) by starting with an array index, for example [0]["powers"][0] .

Other notes

  • JSON is purely a string with a specified data format — it contains only properties, no methods.
  • JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.
  • Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like JSONLint .
  • JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.
  • Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Active learning: Working through a JSON example

So, let's work through an example to show how we could make use of some JSON formatted data on a website.

Getting started

To begin with, make local copies of our heroes.html and style.css files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML, plus a <script> element to contain the JavaScript code we will be writing in this exercise:

We have made our JSON data available on our GitHub, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json .

We are going to load the JSON into our script, and use some nifty DOM manipulation to display it, like this:

Image of a document titled "Super hero squad" (in a fancy font) and subtitled "Hometown: Metro City // Formed: 2016". Three columns below the heading are titled "Molecule Man", "Madame Uppercut", and "Eternal Flame", respectively. Each column lists the hero's secret identity name, age, and superpowers.

Top-level function

The top-level function looks like this:

To obtain the JSON, we use an API called Fetch . This API allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page.

In our function, the first four lines use the Fetch API to fetch the JSON from the server:

  • we declare the requestURL variable to store the GitHub URL
  • we use the URL to initialize a new Request object.
  • we make the network request using the fetch() function, and this returns a Response object
  • we retrieve the response as JSON using the json() function of the Response object.

Note: The fetch() API is asynchronous . We'll learn a lot about asynchronous functions in the next module , but for now, we'll just say that we need to add the keyword async before the name of the function that uses the fetch API, and add the keyword await before the calls to any asynchronous functions.

After all that, the superHeroes variable will contain the JavaScript object based on the JSON. We are then passing that object to two function calls — the first one fills the <header> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <section> .

Populating the header

Now that we've retrieved the JSON data and converted it into a JavaScript object, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:

Here we first create an h1 element with createElement() , set its textContent to equal the squadName property of the object, then append it to the header using appendChild() . We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a template literal containing both the homeTown and formed properties of the object.

Creating the hero information cards

Next, add the following function at the bottom of the code, which creates and displays the superhero cards:

To start with, we store the members property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.

Next, we use a for...of loop to loop through each object in the array. For each one, we:

  • Create several new elements: an <article> , an <h2> , three <p> s, and a <ul> .
  • Set the <h2> to contain the current hero's name .
  • Fill the three paragraphs with their secretIdentity , age , and a line saying "Superpowers:" to introduce the information in the list.
  • Store the powers property in another new constant called superPowers — this contains an array that lists the current hero's superpowers.
  • Use another for...of loop to loop through the current hero's superpowers — for each one we create an <li> element, put the superpower inside it, then put the listItem inside the <ul> element ( myList ) using appendChild() .
  • The very last thing we do is to append the <h2> , <p> s, and <ul> inside the <article> ( myArticle ), then append the <article> inside the <section> . The order in which things are appended is important, as this is the order they will be displayed inside the HTML.

Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)

Note: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our JavaScript object basics article for more information on dot and bracket notation.

Calling the top-level function

Finally, we need to call our top-level populate() function:

Converting between objects and text

The above example was simple in terms of accessing the JavaScript object, because we converted the network response directly into a JavaScript object using response.json() .

But sometimes we aren't so lucky — sometimes we receive a raw JSON string, and we need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we need to convert it to JSON (a string) before sending it. Luckily, these two problems are so common in web development that a built-in JSON object is available in browsers, which contains the following two methods:

  • parse() : Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.
  • stringify() : Accepts an object as a parameter, and returns the equivalent JSON string.

You can see the first one in action in our heroes-finished-json-parse.html example (see the source code ) — this does exactly the same thing as the example we built up earlier, except that:

  • we retrieve the response as text rather than JSON, by calling the text() method of the response
  • we then use parse() to convert the text to a JavaScript object.

The key snippet of code is here:

As you might guess, stringify() works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:

Here we're creating a JavaScript object, then checking what it contains, then converting it to a JSON string using stringify() — saving the return value in a new variable — then checking it again.

Test your skills!

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: JSON .

In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript.

  • JSON reference
  • Fetch API overview
  • Using Fetch
  • HTTP request methods
  • Official JSON website with link to ECMA standard

A beginner's guide to JSON, the data format for the internet

When APIs send data, chances are they send it as JSON objects. Here's a primer on why JSON is how networked applications send data.

Article hero image

As the web grows in popularity and power, so does the amount of data stored and transferred between systems, many of which know nothing about each other. From early on, the format that this data was transferred in mattered, and like the web, the best formats were open standards that anyone could use and contribute to. XML gained early popularity, as it looked like HTML, the foundation of the web. But it was clunky and confusing.

That’s where JSON (JavaScript Object Notation) comes in. If you’ve consumed an API in the last five to ten years, you’ve probably seen JSON data. While the format was first developed in the early 2000s, the first standards were published in 2006. Understanding what JSON is and how it works is a foundational skill for any web developer.

In this article, we’ll cover the basics of what JSON looks like and how to use it in your web applications, as well as talk about serialized JSON—JST and JWT—and the competing data formats.

What JSON looks like

JSON is a human-readable format for storing and transmitting data. As the name implies, it was originally developed for JavaScript, but can be used in any language and is very popular in web applications. The basic structure is built from one or more keys and values:

You’ll often see a collection of key:value pairs enclosed in brackets described as a JSON object. While the key is any string, the value can be a string, number, array, additional object, or the literals, false, true and null. For example, the following is valid JSON:

JSON doesn't have to have only key:value pairs; the specification allows to any value to be passed without a key. However, almost all of the JSON objects that you see will contain key:value pairs.

Using JSON in API calls

One of the most common uses for JSON is when using an API, both in requests and responses. It is much more compact than other standards and allows for easy consumption in web browsers as JavaScript can easily parse JSON strings, only requiring JSON.parse() to start using it.

JSON.parse(string) takes a string of valid JSON and returns a JavaScript object. For example, it can be called on the body of an API response to give you a usable object. The inverse of this function is JSON.stringify(object) which takes a JavaScript object and returns a string of JSON, which can then be transmitted in an API request or response.

JSON isn’t required by REST or GraphQL, both very popular API formats. However, they are often used together, particularly with GraphQL, where it is best practice to use JSON due to it being small and mostly text. If necessary, it compresses very well with GZIP.

GraphQL's requests aren’t made in JSON, instead using a system that resembles JSON, like this

Which will return the relevant data, and if using JSON, it will match very closely:

Using JSON files in JavaScript

In some cases, you may want to load JSON from a file, such as for configuration files or mock data. Using pure JavaScript, it currently isn’t possible to import a JSON file, however a proposal has been created to allow this . In addition, it is a very common feature in bundlers and compilers, like webpack and Babel . Currently, you can get equivalent functionality by exporting a JavaScript Object the same as your desired JSON from a JavaScript file.

export const data = {"foo": "bar"}

Now this object will be stored in the constant, data, and will be accessible throughout your application using import or require statements. Note that this will import a copy of the data, so modifying the object won’t write the data back to the file or allow the modified data to be used in other files.

Accessing and modifying JavaScript objects

Once you have a variable containing your data, in this example data, to access a key’s value inside it, you could use either data.key or data["key"]. Square brackets must be used for array indexing; for example if that value was an array, you could do data.key[0], but data.key.0 wouldn’t work.

Object modification works in the same way. You can just set data.key = "foo" and that key will now have the value “foo”. Although only the final element in the chain of objects can be replaced; for example if you tried to set data.key.foo.bar to something, it would fail as you would first have to set data.key.foo to an object.

Comparison to YAML and XML

JSON isn’t the only web-friendly data standard out there. The major competitor for JSON in APIs is XML. Instead of the following JSON:

in XML, you’d instead have:

JSON was standardized much later than XML, with the specification for XML coming in 1998, whereas Ecma International standardized JSON in 2013. XML was extremely popular and seen in standards such as AJAX (Asynchronous JavaScript and XML) and the XMLHttpRequest function in JavaScript.

XML used by a major API standard: Simple Object Access Protocol (SOAP). This standard can be significantly more verbose than REST and GraphQL, in part due to the usage of XML and because the standard includes more information, such as describing the XML namespace as part of the envelope system. This might be a reason why SOAP usage has declined for years.

what is json representation

Another alternative is YAML, which is much more similar in length to JSON compared to XML, with the same example being:

However, unlike XML, YAML doesn’t really compete with JSON as an API data format. Instead, it’s primarily used for configuration files— Kubernetes primarily uses YAML to configure infrastructure. YAML offers features that JSON doesn’t have, such as comments. Unlike JSON and XML, browsers cannot parse YAML, so a parser would need to be added as a library if you want to use YAML for data interchange.

Signed JSON

While many of JSONs use cases transmit it as clear text, the format can be used for secure data transfers as well. JSON web signatures (JWS) are JSON objects securely signed using either a secret or a public/private key pair. These are composed of a header , payload , and signature .

The header specifies the type of token and the signing algorithm being used. The only required field is alg to specify the encryption algorithm used, but many other keys can be included, such as typ for the type of signature it is.

The payload of a JWS is the information being transmitted and doesn’t need to be formatted in JSON though commonly is.

The signature is constructed by applying the encryption algorithm specified in the header to the base64 versions of the header and payload joined by a dot. The final JWS is then the base64 header, base64 payload, and signature joined by dots. For example:

eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

JSON Web Tokens (JWT) are a special form of a JWS. These are particularly useful for authorization : when a user logs into a website, they will be provided with a JWT. For each subsequent request, they will include this token as a bearer token in the authorization header.

To create a JWT from a JWS, you’ll need to configure each section specifically. In the header , ensure that the typ key is JWT. For the alg key, the options of HS256 (HMAC SHA-256) and none (unencrypted) must be supported by the authorization server in order to be a conforming JWT implementation, so can always be used. Additional algorithms are recommended but not enforced.

In the payload are a series of keys called claims, which are pieces of information about a subject, as JWTs are most commonly used for authentication, this is commonly a user, but could be anything when used for exchanging information.

The signature is then constructed in the same way as all other JWSs.

Compared to Security Assertion Markup Language Tokens (SAML), a similar standard that uses XML, JSON allows for JWTs to be smaller than SAML tokens and is easier to parse due to the use of both tokens in the browser, where JavaScript is the primary language, and can easily parse JSON.

JSON has come to be one of the most popular standards for data interchange, being easy for humans to read while being lightweight to ensure small transmission size. Its success has also been caused by it being equivalent to JavaScript objects, making it simple to process in web frontends. However, JSON isn’t the solution for everything, and alternate standards like YAML are more popular for things like configuration files, so it’s important to consider your purpose before choosing.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object , record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array , vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { left brace and ends with } right brace . Each name is followed by : colon and the name/value pairs are separated by , comma .

what is json representation

An array is an ordered collection of values. An array begins with [ left bracket and ends with ] right bracket . Values are separated by , comma .

what is json representation

A value can be a string in double quotes, or a number , or true or false or null , or an object or an array . These structures can be nested.

what is json representation

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

what is json representation

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

what is json representation

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

what is json representation

json element

value object array string number "true" "false" "null"

object '{' ws '}' '{' members '}'

members member member ',' members

member ws string ws ':' element

array '[' ws ']' '[' elements ']'

elements element element ',' elements

element ws value ws

string '"' characters '"'

characters "" character characters

character '0020' . '10FFFF' - '"' - '\' '\' escape

escape '"' '\' '/' 'b' 'f' 'n' 'r' 't' 'u' hex hex hex hex

hex digit 'A' . 'F' 'a' . 'f'

number integer fraction exponent

integer digit onenine digits '-' digit '-' onenine digits

digits digit digit digits

digit '0' onenine

onenine '1' . '9'

fraction "" '.' digits

exponent "" 'E' sign digits 'e' sign digits

sign "" '+' '-'

ws "" '0020' ws '000A' ws '000D' ws '0009' ws

  • ActionScript3
  • GNATCOLL.JSON
  • JSON for ASP
  • JSON ASP utility class
  • JSON_checker
  • json-parser
  • M's JSON parser
  • ThorsSerializer
  • JSON for Modern C++
  • ArduinoJson
  • JSON library for IoT
  • JSON Support in Qt
  • JsonWax for Qt
  • Qentem-Engine
  • JSON for .NET
  • Manatee Json
  • FastJsonParser
  • Liersch.Json
  • Liersch.JsonSerialization
  • JSON Essentials
  • Redvers COBOL JSON Interface
  • SerializeJSON
  • vibe.data.json
  • json library
  • Delphi Web Utils
  • JSON Delphi Library
  • JSON in TermL
  • json-fortran
  • package json
  • RJson package
  • json package
  • json-taglib
  • json-simple
  • google-gson
  • FOSS Nova JSON
  • Corn CONVERTER
  • Apache johnzon
  • Common Lisp JSON
  • JSON Modules
  • netdata-json
  • Module json
  • NSJSONSerialization
  • json-framework
  • JSON Photoshop Scripting
  • picolisp-json
  • Public.Parser.JSON
  • Public.Parser.JSON2
  • The Python Standard Library
  • metamagic.json
  • json-parsing
  • JSON Utilities
  • json-stream
  • JSON-struct
  • .NET-JSON-Transformer
  • Videos about JSON
  • Videos about the JSON Logo
  • Heresy & Heretical Open Source: A Heretic's Perspective
  • Nota Message Format

What is JSON?

Avatar

JSON, which stands for “JavaScript Object Notation,” is a lightweight, text-based data exchange format that both humans and machines can write and read. Its simplicity and ease of use make it one of the most common formats for transferring data between a server and client—or between different parts of an application.

Here, we’ll clarify the relationship between JSON and JavaScript, before exploring JSON’s syntax and structure in more detail. We’ll also explain the difference between JSON and XML , review the main advantages of JSON, and walk through some best practices for working with JSON.

What is the relationship between JSON and JavaScript?

JSON is derived from JavaScript’s object literal notation, which makes it ideal for data exchange in JavaScript-based applications. However, the majority of modern programming languages include modules, libraries, and functions for generating and parsing JSON data. This versatility supports seamless integration of different systems and technologies, and is one of the main reasons that JSON has become an industry standard.

What is JSON’s structure?

JSON is based on a simple, text-based structure that consists of key-value pairs. Each key is a string, followed by a colon and a corresponding value. Values can be strings, numbers, booleans, objects, arrays, or null, and commas are used to separate key-value pairs within objects, as well as values within arrays. Consider the following example:

This example represents a person as a JSON object. As you can see, JSON objects are enclosed in curly braces. JSON also supports nesting, which allows you to create complex data structures by including objects and arrays within other objects or arrays. In this example, the key “address” has an object as a value, and that object has two keys with strings as values.

JSON also allows the use of whitespace, such as spaces, tabs, and line breaks. Whitespace does not affect a machine’s ability to parse JSON, but it can help make it more human-readable.

What is the difference between JSON and XML?

JSON and XML are both popular data exchange formats, but they have different structures and support different use cases.

As we’ve discussed, JSON uses a simple key-value pair structure that is easy for both humans and machines to read and write. It is primarily used as a means of transmitting data between a web server and client, but it is also used in configuration files. JSON’s data types are limited to strings, numbers, booleans, objects, arrays, and null, which makes it efficient for transmitting and storing structured data without excessive overhead. It also has a hierarchical structure that makes it well-suited for representing complex data relationships.

XML , on the other hand, is a markup language with a more complex syntax that utilizes tags and attributes to define the data’s structure. XML is known for its extensibility and versatility, but its verbosity can lead to larger file sizes and increased parsing complexity. It is therefore less efficient for certain use cases, such as in web applications where performance is paramount.

What are the advantages of JSON?

There are many benefits of working with JSON that make it one of the most beloved data formats today. Some of the advantages include:

  • Human-readability : JSON’s syntax is simple and clear, which makes it more accessible to humans than other data exchange formats. This readability is particularly important if you’re working with configuration files or debugging an error.
  • No excess metadata : JSON is lightweight and doesn’t include any unnecessary metadata or markup. This reduces the size of data, which results in faster data transfer and more efficient data storage.
  • Ease of integration : JSON is compatible with a wide range of programming languages, which allows for easy and efficient data exchange between different software systems and services.
  • Hierarchical structure : JSON’s hierarchical structure—together with its support for a variety of data types—makes it easy to represent complex data relationships.
  • Community support : JSON has a vibrant and active community of users, which means there are numerous resources, libraries, and tools available for working with it.

What are some best practices for working with JSON?

When working with JSON, it’s important to adhere to the following best practices to ensure data integrity, readability, and compatibility across different systems:

  • Prioritize readability : It’s important to maintain clear JSON formatting in order to make it as human-readable as possible. For instance, use indentation and line breaks to structure your objects, and choose descriptive key names that directly communicate the purpose of the data. You should also avoid excessive nesting, which makes the data complex and harder to work with.
  • Use consistent data types : It’s essential to keep your data types consistent in your JSON data in order to avoid unexpected type conversions. You should also use arrays to represent lists of items, rather than object keys with numerical values, as this approach is more durable and easier to work with.
  • Use libraries and tools : There are many programming language libraries and built-in functions that can parse and generate JSON, which reduces the risk of error that comes with doing it manually. You can also use tools and libraries to validate your JSON syntax and catch issues in the early stages of the development process.
  • Validate and sanitize input : If your application receives JSON data from external sources (such as user input), it’s crucial to validate and sanitize it in order to prevent any malicious code from entering the workflow.
  • Avoid circular references : A circular reference occurs when an object contains a reference to itself, which creates an infinite loop. You should therefore avoid circular references when possible, or use techniques like object cloning with reference tracking if necessary.
  • Minimize data size : If data size is critical, consider using minification techniques to remove unnecessary whitespace, which will reduce the overall size of the JSON for transmission or storage.

Avatar

The Postman Team

Today, more than 30 million developers use the Postman API Platform. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

View all posts by The Postman Team →

What do you think about this topic? Tell us in a comment below.

Comment Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed .

You might also like

What is protobuf.

Avatar

Protobuf, which is short for “Protocol Buffers,” is an efficient, language-agnostic data serialization mechanism. It enables developers to define structured data in…

How ADVICEment uses Postman tests to poll and trigger multiple API requests

Avatar

This is a guest post written by Igor Rodionov, founder of ADVICEment. In the dynamic realm of API development, there are instances…

Measure your Postman Collection’s quality with the Postman API and Spectral rules

Avatar

Postman Collections are an excellent tool for collaborating with users in the API design, development, testing, and documentation processes. You can share…

Postman v11 is here!

It's jam-packed with updates to help you collaborate on your APIs, augment yourself with AI, and more.

  • Artificial Intelligence
  • Generative AI
  • Cloud Computing
  • Data Management
  • Emerging Technology
  • Technology Industry
  • Software Development
  • Microsoft .NET
  • Development Tools
  • Open Source
  • Programming Languages
  • Enterprise Buyer’s Guides
  • Newsletters
  • Foundry Careers
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Copyright Notice
  • Member Preferences
  • About AdChoices
  • E-commerce Affiliate Relationships
  • Your California Privacy Rights

Our Network

  • Computerworld
  • Network World

Matthew Tyson

What is JSON? The universal data format

Json is the leading data interchange format for web applications and more. here’s what you need to know about javascript object notation..

JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data [logo]

JSON, or JavaScript Object Notation, is a format used to represent data. It was introduced in the early 2000s as part of JavaScript and gradually expanded to become the most common medium for describing and exchanging text-based data. Today, JSON is the universal standard of data exchange. It is found in every area of programming, including front-end and server-side development, systems, middleware, and databases.

This article introduces you to JSON. You’ll get an overview of the technology, find out how it compares to similar standards like XML, YAML, and CSV, and see examples of JSON in a variety of programs and use cases.

A little bit of history

JSON was initially developed as a format for communicating between JavaScript clients and back-end servers. It quickly gained popularity as a human-readable format that front-end programmers could use to communicate with the back end using a terse, standardized format. Developers also discovered that JSON was very flexible: you could add, remove, and update fields ad hoc. (That flexibility came at the cost of safety, which was later addressed with the JSON schema.)

In a curious turn, JSON was popularized by the AJAX revolution . Strange, given the emphasis on XML, but it was JSON that made AJAX really shine. Using REST as the convention for APIs and JSON as the medium for exchange proved a potent combination for balancing simplicity, flexibility, and consistency.

Next, JSON spread from front-end JavaScript to client-server communication, and from there to system config files, back-end languages, and all the way to databases. JSON even helped spur the NoSQL movement that revolutionized data storage. It turned out that database administrators also enjoyed JSON’s flexibility and ease of programming.

Today, document-oriented data stores like MongoDB provide an API that works with JSON-like data structures. In an interview in early 2022, MongoDB CTO Mark Porter noted that, from his perspective, JSON is still pushing the frontier of data .  Not bad for a data format that started with a humble curly brace and a colon.

Why developers use JSON

No matter what type of program or use case they’re working on, software developers need a way to describe and exchange data. This need is found in databases, business logic, user interfaces, and in all systems communication. There are many approaches to structuring data for exchange. The two broad camps are binary and text-based data. JSON is a text-based format, so it is readable by both people and machines.

JSON is a wildly successful way of formatting data for several reasons. First, it’s native to JavaScript, and it’s used inside of JavaScript programs as JSON literals. You can also use JSON with other programming languages, so it’s useful for data exchange between heterogeneous systems. Finally, it is human readable. For a language data structure, JSON is an incredibly versatile tool. It is also fairly painless to use, especially when compared to other formats. 

How JSON works

When you enter your username and password into a form on a web page, you are interacting with an object with two fields: username and password. As an example, consider the login page in Figure 1.

A simple login page.

Figure 1. A simple login page.

Listing 1 shows this page described using JSON.

Listing 1. JSON for a login page

Everything inside of the braces or squiggly brackets ( {…} ) belongs to the same object. An object , in this case, refers in the most general sense to a “single thing.” Inside the braces are the properties that belong to the thing. Each property has two parts: a name and a value, separated by a colon. These are known as the keys and values. In Listing 1, “username” is a key and “Bilbo Baggins” is a value.

The key takeaway here is that JSON does everything necessary to handle the need—in this case, holding the information in the form—without a lot of extra information. You can glance at this JSON file and understand it. That is why we say that JSON is concise . Conciseness also makes JSON an excellent format for sending over the wire. 

JSON vs. XML

JSON was created as an alternative to XML, which was once the dominant format for data exchange. The login form in Listing 2 is described using XML.

Listing 2. Login form in XML

Yikes!  Just looking at this form is tiring. Imagine having to create and parse it in code. In contrast, using JSON in JavaScript is dead simple. Try it out. Hit F12 in your browser to open a JavaScript console, then paste in the JSON shown in Listing 3.

Listing 3. Using JSON in JavaScript

XML is hard to read and leaves much to be desired in terms of coding agility. JSON was created to resolve these issues. It’s no wonder it has more or less supplanted XML.

JSON vs. YAML and CSV

Two data formats sometimes compared to JSON are YAML and CSV. The two formats are on opposite ends of the temporal spectrum. CSV is an ancient, pre-digital format that eventually found its way to being used in computers. YAML was inspired by JSON and is something of its conceptual descendant.

CSV is a simple list of values, with each entry denoted by a comma or other separator character, with an optional first row of header fields. It is rather limited as a medium of exchange and programming structure, but it is still useful for outputting large amounts of data to disk. And, of course, CSV’s organization of tabular data is perfect for things like spreadsheets.

YAML is actually a superset of JSON, meaning it will support anything JSON supports. But YAML also supports a more stripped-down syntax, intended to be even more concise than JSON. For example, YAML uses indentation for hierarchy, forgoing the braces. Although YML is sometimes used as a data exchange format, its biggest use case is in configuration files.

Complex JSON: Nesting, objects, and arrays

So far, you’ve only seen examples of JSON used with shallow (or simple) objects. That just means every field on the object holds the value of a primitive. JSON is also capable of modeling arbitrary complex data structures such as object graphs and cyclic graphs—that is, structures with circular references. In this section, you’ll see examples of complex modeling via nesting, object references, and arrays.

JSON with nested objects

Listing 4 shows how to define nested JSON objects.

Listing 4. Nested JSON

The bestfriend property in Listing 4 refers to another object, which is defined inline as a JSON literal.

JSON with object references

Now consider Listing 5, where instead of holding a name in the bestfriend property, we hold a reference to the actual object.

Listing 5. An object reference

In Listing 5, we put the handle to the merry object on the bestfriend property. Then, we are able to obtain the actual merry object off the pippin object via the bestfriend property. We obtained the name off the merry object with the name property. This is called traversing the object graph , which is done using the dot operator.

JSON with arrays

Another type of structure that JSON properties can have is arrays. These look just like JavaScript arrays and are denoted with a square bracket, as shown in Listing 6.

Listing 6. An array property

Of course, arrays may hold references to other objects, as well. With these two structures, JSON can model any range of complex object relations.

Parsing and generating JSON

Parsing and generating JSON means reading it and creating it, respectively. You’ve seen JSON.stringify() in action already. That is the built-in mechanism for JavaScript programs to take an in-memory object representation and turn it into a JSON string. To go in the other direction—that is, take a JSON string and turn it into an in-memory object—you use JSON.parse() .

In most other languages, it’s necessary to use a third-party library for parsing and generating. For example, in Java there are numerous libraries , but the most popular are Jackson and GSON . These libraries are more complex than stringify and parse in JavaScript, but they also offer advanced capabilities such as mapping to and from custom types and dealing with other data formats.

In JavaScript, it is common to send and receive JSON to servers. For example with the built in fetch() API.  When doing so, you can automatically parse the response, as shown in Listing 7. 

Listing 7. Parsing a JSON response with fetch()

Once you turn JSON into an in-memory data structure, be it JavaScript or another language, you can employ the APIs for manipulating the structure. For example, in JavaScript, the JSON parsed in Listing 7 would be accessed like any other JavaScript object—perhaps by looping through data.keys or accessing known properties on the data object.

JSON schema and JSON formatter

JavaScript and JSON are incredibly flexible, but sometimes you need more structure than they provide. In a language like Java, strong typing and abstract types (like interfaces) help structure large-scale programs. In SQL stores, a schema provides a similar structure. If you need more structure in your JSON documents, you can use JSON schema to explicitly define the characteristics of your JSON objects. Once defined, you can use the schema to validate object instances and ensure that they conform to the schema.

Another issue is dealing with machine-processed JSON that is minified and illegible. Fortunately, this problem is easy to solve. Just jump over to the JSON Formatter & Validator (I like this tool but there are others), paste in your JSON, and hit the Process button. You’ll see a human-readable version that you can use. Most IDEs also have a built-in JavaScript formatter to format your JSON.

Using JSON with TypeScript

TypeScript allows for defining types and interfaces, so there are times when using JSON with TypeScript is useful. A class, like a schema, outlines the acceptable properties of an instance of a given type. In plain JavaScript there’s no way to restrict properties and their types. JavaScript classes are like suggestions; the programmer can set them now and modify the JSON later. A TypeScript class, however, enforces what properties the JSON can have and what types they can be.

JSON is one of the most essential technologies used in the modern software landscape. It is crucial to JavaScript but also used as a common mode of interaction between a wide range of technologies. Fortunately, the very thing that makes JSON so useful makes it relatively easy to understand. It is a concise and readable format for representing textual data.

Related content

Kotlin update shines on garbage collector, what ai regulations mean for software developers, deno 1.46 simplifies cli, developing agile etl flows with ballerina.

Matthew Tyson

Matthew Tyson is a founder of Dark Horse Group, Inc. He believes in people-first technology. When not playing guitar, Matt explores the backcountry and the philosophical hinterlands. He has written for JavaWorld since 2007.

More from this author

State of javascript: insights from the latest javascript developer survey, functional programming with java collections, full-stack development with java, react, and spring boot, part 3, full-stack development with java, react, and spring boot, part 2, full-stack development with java, react, and spring boot, part 1, frequently sought solutions for javascript, progressive web app essentials: service worker background sync, intro to multithreaded javascript, most popular authors.

what is json representation

Show me more

Are you the boss of your feed.

Image

The definitive guide to data pipelines

Image

The slow evolution of enterprise tech

Image

The basics of Pillow, Python's image manipulation library

Image

How to use the watch command

Image

How to use dbm to stash data quickly in Python

Image

  • Full Stack Course
  • React Native
  • CSS Frameworks
  • JS Frameworks
  • Web Development

What is JSON

JSON, short for JavaScript Object Notation , is a lightweight data-interchange format used for transmitting and storing data. It has become a standard format for web-based APIs due to its simplicity and ease of use.

What is JSON?

JSON is a text-based data format that is easy for humans to read and write, as well as parse and generate programmatically. It is based on a subset of JavaScript’s object literal syntax but is language-independent, making it widely adopted in various programming languages beyond JavaScript.

JSON Structure

Data Representation : JSON represents data in key-value pairs. Each key is a string enclosed in double quotes, followed by a colon, and then its corresponding value. Values can be strings, numbers, arrays, objects, booleans, or null.

Why do we use JSON?

  • Lightweight and Human-Readable : JSON’s syntax is simple and human-readable, making it easy to understand and work with both by developers and machines.
  • Data Interchange Format : JSON is commonly used for transmitting data between a server and a client in web applications. It’s often used in APIs to send and receive structured data.
  • Language Independence : JSON is language-independent, meaning it can be used with any programming language that has JSON parsing capabilities.
  • Supported Data Types : JSON supports various data types such as strings, numbers, booleans, arrays, objects, and null values, making it versatile for representing complex data structures.
  • Compatibility : Most modern programming languages provide built-in support for JSON parsing and serialization, making it easy to work with JSON data in different environments.
  • Web APIs : JSON is widely used in web APIs to format data responses sent from a server to a client or vice versa. APIs often return JSON-formatted data for easy consumption by front-end applications.
  • Configuration Files : JSON is used in configuration files for web applications, software settings, and data storage due to its readability and ease of editing.
  • Data Storage : JSON is also used for storing and exchanging data in NoSQL databases like MongoDB, as it aligns well with document-based data structures.

JSON Data Types

Data Type Example Description
String “name”: “Raj” Represents textual data enclosed in double quotes.
Number “age”: 30 Represents numeric values (integer or floating-point).
Boolean “isStudent”: false Represents true or false values.
Array “courses”: [“Math”, “Science”] Ordered collection of values enclosed in square brackets.
Object “address”: {
“city”: “New York”,
“zipcode”: “10001”
}
Unordered collection of key-value pairs enclosed in curly braces.
Null “description”: null Represents an empty or undefined value.

Converting a JSON Text to a JavaScript Object

In JavaScript, you can parse a JSON text into a JavaScript object using the JSON.parse() method:

JavaScript Object:

JSON vs XML

Aspect JSON XML
Format Lightweight, easy to read and write Hierarchical, verbose syntax
Data Types Supports basic data types Supports a wide range of data types
Readability Easier for humans to read and write More complex and verbose structure
Structure Typically simpler and flatter Hierarchical with nested elements
Syntax Uses key-value pairs Uses tags, attributes, and elements
Parsing Faster and more efficient Slower due to its complex structure
Scalability Ideal for web APIs and data exchange Suitable for complex data structures
Extensibility Limited extensibility High extensibility and flexibility
Usage Commonly used in modern web apps Widely used in data interchange and storage

JSON is a versatile and widely adopted data format that plays a crucial role in modern web development, especially in building APIs and handling data interchange between different systems. Its simplicity, readability, and compatibility with various programming languages make it a preferred choice for developers working with data-driven applications.

Please Login to comment...

Similar reads.

  • Web Technologies
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

JSON methods, toJSON

Let’s say we have a complex object, and we’d like to convert it into a string, to send it over a network, or just to output it for logging purposes.

Naturally, such a string should include all important properties.

We could implement the conversion like this:

…But in the process of development, new properties are added, old properties are renamed and removed. Updating such toString every time can become a pain. We could try to loop over properties in it, but what if the object is complex and has nested objects in properties? We’d need to implement their conversion as well.

Luckily, there’s no need to write the code to handle all this. The task has been solved already.

JSON.stringify

The JSON (JavaScript Object Notation) is a general format to represent values and objects. It is described as in RFC 4627 standard. Initially it was made for JavaScript, but many other languages have libraries to handle it as well. So it’s easy to use JSON for data exchange when the client uses JavaScript and the server is written on Ruby/PHP/Java/Whatever.

JavaScript provides methods:

  • JSON.stringify to convert objects into JSON.
  • JSON.parse to convert JSON back into an object.

For instance, here we JSON.stringify a student:

The method JSON.stringify(student) takes the object and converts it into a string.

The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object. We are ready to send it over the wire or put into a plain data store.

Please note that a JSON-encoded object has several important differences from the object literal:

  • Strings use double quotes. No single quotes or backticks in JSON. So 'John' becomes "John" .
  • Object property names are double-quoted also. That’s obligatory. So age:30 becomes "age":30 .

JSON.stringify can be applied to primitives as well.

JSON supports following data types:

  • Objects { ... }
  • Arrays [ ... ]
  • boolean values true/false ,

For instance:

JSON is data-only language-independent specification, so some JavaScript-specific object properties are skipped by JSON.stringify .

  • Function properties (methods).
  • Symbolic keys and values.
  • Properties that store undefined .

Usually that’s fine. If that’s not what we want, then soon we’ll see how to customize the process.

The great thing is that nested objects are supported and converted automatically.

The important limitation: there must be no circular references.

Here, the conversion fails, because of circular reference: room.occupiedBy references meetup , and meetup.place references room :

Excluding and transforming: replacer

The full syntax of JSON.stringify is:

Most of the time, JSON.stringify is used with the first argument only. But if we need to fine-tune the replacement process, like to filter out circular references, we can use the second argument of JSON.stringify .

If we pass an array of properties to it, only these properties will be encoded.

Here we are probably too strict. The property list is applied to the whole object structure. So the objects in participants are empty, because name is not in the list.

Let’s include in the list every property except room.occupiedBy that would cause the circular reference:

Now everything except occupiedBy is serialized. But the list of properties is quite long.

Fortunately, we can use a function instead of an array as the replacer .

The function will be called for every (key, value) pair and should return the “replaced” value, which will be used instead of the original one. Or undefined if the value is to be skipped.

In our case, we can return value “as is” for everything except occupiedBy . To ignore occupiedBy , the code below returns undefined :

Please note that replacer function gets every key/value pair including nested objects and array items. It is applied recursively. The value of this inside replacer is the object that contains the current property.

The first call is special. It is made using a special “wrapper object”: {"": meetup} . In other words, the first (key, value) pair has an empty key, and the value is the target object as a whole. That’s why the first line is ":[object Object]" in the example above.

The idea is to provide as much power for replacer as possible: it has a chance to analyze and replace/skip even the whole object if necessary.

Formatting: space

The third argument of JSON.stringify(value, replacer, space) is the number of spaces to use for pretty formatting.

Previously, all stringified objects had no indents and extra spaces. That’s fine if we want to send an object over a network. The space argument is used exclusively for a nice output.

Here space = 2 tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside an object:

The third argument can also be a string. In this case, the string is used for indentation instead of a number of spaces.

The space parameter is used solely for logging and nice-output purposes.

Custom “toJSON”

Like toString for string conversion, an object may provide method toJSON for to-JSON conversion. JSON.stringify automatically calls it if available.

Here we can see that date (1) became a string. That’s because all dates have a built-in toJSON method which returns such kind of string.

Now let’s add a custom toJSON for our object room (2) :

As we can see, toJSON is used both for the direct call JSON.stringify(room) and when room is nested in another encoded object.

To decode a JSON-string, we need another method named JSON.parse .

The syntax:

Or for nested objects:

The JSON may be as complex as necessary, objects and arrays can include other objects and arrays. But they must obey the same JSON format.

Here are typical mistakes in hand-written JSON (sometimes we have to write it for debugging purposes):

Besides, JSON does not support comments. Adding a comment to JSON makes it invalid.

There’s another format named JSON5 , which allows unquoted keys, comments etc. But this is a standalone library, not in the specification of the language.

The regular JSON is that strict not because its developers are lazy, but to allow easy, reliable and very fast implementations of the parsing algorithm.

Using reviver

Imagine, we got a stringified meetup object from the server.

It looks like this:

…And now we need to deserialize it, to turn back into JavaScript object.

Let’s do it by calling JSON.parse :

Whoops! An error!

The value of meetup.date is a string, not a Date object. How could JSON.parse know that it should transform that string into a Date ?

Let’s pass to JSON.parse the reviving function as the second argument, that returns all values “as is”, but date will become a Date :

By the way, that works for nested objects as well:

  • JSON is a data format that has its own independent standard and libraries for most programming languages.
  • JSON supports plain objects, arrays, strings, numbers, booleans, and null .
  • JavaScript provides methods JSON.stringify to serialize into JSON and JSON.parse to read from JSON.
  • Both methods support transformer functions for smart reading/writing.
  • If an object has toJSON , then it is called by JSON.stringify .

Turn the object into JSON and back

Turn the user into JSON and then read it back into another variable.

Exclude backreferences

In simple cases of circular references, we can exclude an offending property from serialization by its name.

But sometimes we can’t just use the name, as it may be used both in circular references and normal properties. So we can check the property by its value.

Write replacer function to stringify everything, but remove properties that reference meetup :

Here we also need to test key=="" to exclude the first call where it is normal that value is meetup .

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

To get our most up-to-date content please access our documentation

JSON Explained – What is JSON (JavaScript Object Notation)?

  • Announcements , News

If you’re a developer, you’ve likely heard of JSON. JSON, which stands for JavaScript Object Notation, is a text-based data interchange format that’s based on JavaScript object syntax. We’ve briefly touched on JSON in our “ What is JavaScript? ” article, and in our guide comparing Infura alternatives . Nevertheless, JSON is important enough for web development (and Web3 development) that it deserves a guide of its own. As such, let’s dive into JavaScript Object Notation to answer “what is JSON?”.

When working with Moralis, however, you don’t even need to know all the nitty-gritty details of JSON. You’ll likely already know that the Moralis Real-Time Database enables you to store JSON data, and sync any data between users in real-time. Moralis is all about ease of use, so the Moralis SDK is designed so that you won’t need to worry about how data is stored. However, there are situations when it can be helpful to get some insight into how data is stored on the Moralis platform. Specifically, Moralis stores internal data as JSON, meaning that any type of data that can be converted to JSON can be stored on Moralis. If you want more technical information about how Moralis handles data storage internally, be sure to check out our official documentation on Data Storage . Sign up for Moralis for free today to supercharge your Web3 and dApp development! More information about how Moralis works with files is available in the following YouTube Moralis file tutorial:

Understanding JavaScript Object Notation

JSON is an important part of any developer’s practical toolkit. If you are not familiar with it yet, it would be great to learn a few basics so you can understand the principles behind JSON and what JSON is used for. The topic will likely turn up in the course of developing a web app or any kind of website, so it’s better to be prepared. JSON offers several advantages that give you an edge in developing better and faster websites, so it’s useful to understand JSON.

what is json representation

As stated before, JSON is an acronym that stands for JavaScript Object Notation. The acronym was coined by a company called State Software and is further attributed to its co-founder Douglas Crockford, who originally popularized JSON. As the name has no vowels, some people are unsure of how to pronounce it – whether it’s pronounced like the name “Jason” or more like how it’s commonly read, which is with emphasis on the second syllable: “Jay-sawn”. Some references cite that the correct pronunciation is “Jason” but its originator is also on record saying that he doesn’t care. As such, the “correct pronunciation” of JSON is an old case of “potay-to, potah-to”.

JSON is worth studying because of its usefulness in organizing and sending data, making it easier for anyone to structure or configure data in the process of building whatever they want on the web. It allows you to create more interactive websites and lightens the data load.

The format was created because, at one point, there arose a clear need for a server-to-browser communication protocol that was stateless and could work in real-time. Remember Flash? Sounds a bit archaic now, doesn’t it? At one point, Flash and Java “ applets ” were mainly used for this purpose. Not anymore.

What is JSON? A Bit of Backstory

Today, JSON has surpassed XML as the world’s preferred data interchange format for web services and applications. Nevertheless, this wasn’t always the case. Let’s, therefore, go back to the humble beginnings of what we today know as JSON. One of the earliest websites that applied a similar principle to today’s JSON libraries was a game called Cartoon Orbit, created for Cartoon Network. It opened the doors to a new type of interactivity. It was a digital asset trading game for kids. The game used a browser-side plug-in that had its proprietary messaging format used in the manipulation of Dynamic HTML elements. Around this time, developers were still in the process of discovering the early capabilities of Ajax. They found a way to use frames to pass information into a user browser’s visual field without the previous need to constantly refresh the visual context of a web application. This aha moment led to the realization of real-time web applications using only standard HTTP, HTML, and JavaScript capabilities of the popular browsers of that time. 

what is json representation

These early origins help you understand what JSON is used for. It evolved as a tool to solve similar issues and was inspired by such early attempts.

What is JSON Used For?

The answer for what JSON could be used for came soon therafter. In a press release back in 2002, State Software announced a State Application Framework, or SAF, that claimed to reduce the time that developers required to create interactive web applications. This new SAF also had the advantages of providing a better user experience and reducing deployment costs. 

what is json representation

Developers would for the first time be able to build “distributed sessionful applications”. Back then, web interactivity was defined differently than today. Interactivity didn’t seem like interactivity at all. Websites were still slow and cumbersome. This was partly because of the unnecessary complexity behind web applications. User experience undoubtedly paid for such inefficiencies. E-commerce or online transactions had to be done one page at a time – meaning, they were static and tedious. The entire process needed to be brought from the client to the server and back. This endless process of passing on data and a web running one page at a time was coming to an end.

Advantages of JavaScript Open Notation 

This new structural framework’s dynamic features dramatically changed the static processes of old. In a way, this, which would lead to the advent of JSON, became a move from statelessness to “statefulness”. One of the new advantages of such a framework, apart from the obvious seamlessness and interactivity on the part of the user, was its ability to speed up development on the creators’ side. It enabled projects to reduce time to market and therefore cut costs on labor and other operations. It also allowed one to cut down on hardware and software, further lowering costs. 

For the first time, we had web applications that appeared smoother to interact with. It was all about the ease of the end-user.  One could feel the step reduction by just interacting with a site. A cumbersome series of dozens of steps could be reduced to one or two. While it simplified the process, it also improved it. This had tremendous implications for supply chain inventories which could now be accessed and managed in real-time.

Linear and serial processes were replaced by real-time interactivity delivered by constant two-way interaction. The new process of structuring data created a leap from static pages to interactive ones that allowed for dynamic updates. 

A Two-Way Communication Layer

The principle behind the new framework was to introduce a new two-way abstraction or duplex communication layer, which creates an interactive session with the browser of an end-user.

Once this interactive session is established, it opens up a faster way of updating the site. The persistent layer or connection does away with the old process of constantly having to reload a website. It held a duplex connection to web servers by holding two HTTP connections open. It recycled the HTTP connections before set browser time-outs if it saw that there was no further interchange of data. Through this framework, one can transmit changed content without having to go the long route. 

The new framework built on Java is also scalable and redundant, capable of using multiple “state session servers” to hold active sessions with a browser. It’s a combination of less information plus a persistent connection. The idea proposed a triple win for users, companies, and software developers. All of these attributes help answer the question “What is JSON?” and give an idea of what JSON is used for – how it eventually became an indispensable tool for developers using different kinds of programming languages.

JavaScript Object Notation is Born

Everything described above made up the beginnings of JSON, or JavaScript Object Notation. The format was soon popularized as it offered a clear advantage to previous ways of updating and reloading a site. 

So, what is JSON, or JavaScript Object Notation? Well, JSON was based on JavaScript’s scripting language, specifically the subset Standard ECMA-262 3rd Edition of December 1999, and knowledge of JavaScript is essential as it is often used together with JSON. However, this is not saying that JSON is a language in itself. It is a data format that is language-independent and language-agnostic.

The language-independent data format allows the code for parsing and generating JSON data to be written in many programming languages. The JSON libraries are listed according to language on the official JSON site.

In terms of usability, the JSON license contains a simple clause, added by Douglas Crockford himself, stating “The Software shall be used for Good, not Evil”. 

What is JSON? A Simple Definition

In its simplest definition, JSON – or JavaScript Object Notation – is a way to store and transmit structured data in a simplified and text-based fashion. Its syntax is deliberately made simple so that it allows you to store a variety of data in varying degrees of simplicity or complexity (whichever perspective you approach it). The extension “.json” is used in its filenames. With JSON, you can store single numbers, strings, arrays, and objects. How does JSON do this? It can accomplish this method of storage with a simple string of plain text. 

what is json representation

JSON also allows nesting of objects and arrays. This gives you the capability to build more complex data structures. When a JSON string is created, it makes it easier to send data to an application or computer. Plain text makes the whole thing simple to execute.

The principle is based on a manner of defining objects and arrays. Objects in JSON have a high level of similarity and are analogous to hashes or associated arrays that are used in other programming languages.

Types of Data Used in JavaScript Object Notation

Part of understanding “What is JSON?” is to grasp the types of values or data that can be included in this format. They are as follows:

First, you have numbers. These include real numbers, integers, and floating numbers. The second category is strings. Strings are a sequence of any text or Unicode characters that have delimitations in the form of double-quotation marks and support backslash escapement. The third category is nulls. Nulls simply denote that the associated variable has no value. The fourth category is objects. Objects are collections of key-value pairs, otherwise known as name-value pairs or attribute-value pairs. They are used to represent associative arrays and are separated by commas and enclosed in curly brackets. The fifth category is Booleans. Boolean data represents true or false values. The sixth category is arrays. Arrays are ordered sequences of values that are separated. 

What JSON is Used For

To understand what JSON is used for, first, you have to look at the advantages that it confers any web project. 

what is json representation

Pluses of using JSON or JavaScript Object Notation:

  • Easy mapping into data structures that are utilized by popular programming languages, such as numbers, nulls, strings, arrays, booleans, and associative arrays
  • Almost all programming languages have libraries or functions that can read and write structures of JSON
  • Simple and compact
  • It was made to be user-friendly for both people and computers
  • It’s flexible

Specifics of what JSON is Used For

JSON, or JavaScript Object Notation, can be used with a multitude of modern programming languages in several different ways. While going into each language is beyond the scope of this article, know that if you search “What is JSON” you will be directed to many applications in different languages. 

  • Data Transfers. JSON helps you move server data. It also allows you to transmit data between servers and web applications.
  • Serializing Data. JSON is a convenient way to serialize structured data and its transmission. The file format simplifies the process.
  • Omitting the Need for Page Refresh. With JSON, you don’t need to refresh a web page constantly. You can perform asynchronous data calls, thus making the process of data retrieval more efficient. 
  • The JSON format is used for the retrieval of public data by restful APIs and web services
  • JavaScript-related applications

JSON and JavaScript Applications

If you use JavaScript or are interested in learning JavaScript, you’ll be happy to know that JSON is widely used in JavaScript applications. Website and browser extensions are part of such applications. It is also used for writing JS-based applications that involve browser add-ons. 

As JSON in itself, though not a programming language, is based on a subset of JavaScript’s scripting language, it would be helpful for you to understand JavaScript better on the way to mastering the use of JSON. JSON’s syntax is based on the object notation from JavaScript, so you’ll find that you won’t be needing much extra software if you intend to work with JSON within JS. If you want to stay at the forefront of web development, you’ll already know that Web3 is the next big thing. However, traditional Web3 development can seem prohibitively difficult. This is where Moralis comes in. 

what is json representation

Moralis is a fully managed, infinitely scalable Web3 backend infrastructure. As such, you do not need to reinvent the wheel when creating dApps or Web3 apps. Instead, Moralis allows developers to focus on the frontend side of things. Consequently, developers do not need to waste time setting up, managing and maintaining their own Web3 backends. Instead, Moralis handles all the heavy lifting. This allows you to create dApps and Web3 apps in hours and minutes, rather than months and weeks. What’s more, Moralis features full support for JSON, along with many other innovative technologies – such as Moralis Speedy Nodes , the Moralis Deep Index API, the Moralis NFT API , and much, much more.

Understand What JSON is by Learning JavaScript

Did you know that JSON can be easily translated to JS? If you are new to web development or wish to enhance your skills further, you can look up Ivan on Tech Academy’s amazing, beginner-friendly JavaScript course .

what is json representation

You can learn HTML and JavaScript all in one, and proceed to understand how it is used in the hottest trends right now like blockchain development. Another benefit to learning JavaScript is that you can move onto learning Solidity , which also bases its syntax on JS. The languages are very similar. 

How to Format a JSON File

To understand JSON formatting, you need to understand its basic syntax and features. While we can’t cover the entire scope of how to format a JSON file as well as its use within different programming languages, we can get started on understanding the rules behind JSON’s syntax.

Syntax Rules of JSON:

  • All data should come in name/value pairs
  • All of the data has to be separated by commas
  • The array type of data should be held by square brackets
  • The object-type data should be held by curly braces

In JSON, whitespace is allowed. Whitespace is defined plainly as that space that is ignored in between the elements of the syntax. The characters or keyboard elements that are considered whitespace are carriage returns, line feeds, horizontal tabs, and spaces. 

Comments have been excluded from the JSON format. They were excluded from the design by Crockford himself for better interoperability, avoiding the possibility of people using them to hold parsing directives. 

Writing JSON Strings

With an idea of JSON’s syntax rules, you can proceed to learn how to write JSON strings. You can practice this and view further details and examples on the JSON website.

How to Format a JSON File With Notepad++

Notepad++ is a relatively common programmer text editor for Windows. Given its accessibility, it should be a convenient tool for formatting JSON. 

JSON is supposedly a human-readable format but more often than not, it just comes as a long string, without spaces or a wall of text that is hardly human-friendly at all. So with that in mind, there are tools that make it easier for us to read it and guide us on how to format a JSON file. 

When JSON is minified, or stripped of spaces and line breaks, for faster network transfer, it becomes impossible for humans to easily read. 

You can try the JSONViewer plugin for Notepad++ to fix this problem. As Notepad++ is free and open-source with many great plugins to choose from, it’s a relatively popular choice.

Get the Plugin on Notepad++

Go on the plugins menu and click Show Plugin Manager. A dialog box allows you to search the plugins. To find what you’re looking for simply search JSON. Just find the plugin JSONViewer and hit install. This is your first simple step in learning how to format a JSON file.

what is json representation

Bear in mind that with JSONViewer you need to select the entire JSON text before you proceed to formatting. This is a really important step. Nothing will happen if you don’t select the text. 

How to Format a JSON File Using JSONViewer

After selecting, you go to JSONViewer, then click Format JSON. Instantly, you should see your JSON nicely displayed on screen in an easy-to-read formatted version. JSON Viewer also has a tree view of the file. 

How to Format a JSON File Using JSTool

Another plugin option you can use is JSTool. JSTool has the added feature of allowing you to fold the JSON. If you are wondering which Notebook++ plugin best assists you on how to format a JSON file, this could be it. 

what is json representation

The folding feature makes it easier for you to fold the text or hide it, so you don’t have to view the whole thing. JSTool also has the advantage of not having to let you do the selection before formatting. It does the selection automatically. JSTool has a minifier option, which JSONViewer does not have. The minifier brings it back to its compressed form without spaces. 

How to Format a JSON File using Other Web-based Tools

Now that you’re already familiar with how to format a JSON file using Notepad++, you can explore other options. Numerous websites help you do that. Outside of Notepad++, there are other formatters that allow you to format JSON data to make it easier to read during a debugging process and can work with a variety of programming languages. Several free web-based tools can help you edit, view, and show you how to format a JSON file outside of the ones used in our tutorial. There are also open-source projects that can be used as annotators, validators, and reformatters of JSON. 

Why Learn JavaScript Open Notation?

Ultimately, JavaScript Open Notation was intended to simplify and lighten the process of data transfer in order to build speed lanes between man and machine—or man and code, browser and server. Its sparse yet systematic way of organizing data has led to many benefits in user experience and on the creator or manufacturer side, to ship products faster. Learning and understanding JSON, and being able to format it while working with various programming languages is a skill that will optimize any development endeavor and will lead to exponential advantages down the road.

When you use Moralis, you do not need to learn all the specifics of JavaScript Open Notation. However, if you’ve appreciated this article, be sure to check out our other more technical deep-dives on the Moralis blog. The Moralis blog is updated on a daily basis with completely free, in-depth articles such as “ What is Hardhat? ”, “ What is IPFS? ”, “ MetaMask Explained ”, “ What are Geth Nodes? ” and much more!

Moralis Money

Related Articles

Moralis Releases Transaction Labeling

Moralis to Add Aptos Support

Moralis Introduces Extended RPC Methods

Moralis Introduces Base Support

Moralis Launches DeFi Positions

Moralis Launches NFT Image Preview Feature

Introducing Token Logos for Token API

Moralis is Adding Support for Flow

Moralis Introduces Support for the Optimism Network

Parse JSON: What is JSON parsing and how does it work?

When you parse JSON, you convert a string containing a JSON document into a structured data object that you can operate on. Learn how this works.

  • Parse JSON online

Do you just need to parse your JSON online to inspect it? Paste your JSON in the following editor:

  • What does it mean to parse JSON?

JSON is a data format used to serialize data. Serialization is the process of converting a data object that exists in computer memory into a series of bytes that can be easily persisted or transmitted. Serialized data can be stored on disk, in a database, or sent over between machines, like from a server to a browser. There are various data formats that can be used to serialize data, for example readable formats like JSON, XML, CSV or binary formats like BSON or MS Word .doc files. In this article, we will talk about JSON only. The serialization process has two directions:

  • Serialization is the process of turning a data object into a series of bytes. In the context of JSON data, this is often called stringifying JSON .
  • Deserializing is the process of turning a series of bytes into a data object. In the context of JSON data, this is often called parsing JSON .

In the following schematic image you see an object in memory of say a web application in your browser. It is an object holding some information about a user. Serialization converts the data into a piece of text that holds all information and the structure of the data: an object with some properties, and the “scores” property is a list holding values. The JSON data holds all information needed to parse the data into an object in memory again.

  • Why do we need to parse JSON?

For example when you are a web developer, building a web application, you will typically fetch data from a server. For example on a web shop, the application will retrieve a list with products that the user is searching for. The JSON data that you will receive is just “a piece of text” at first. Before you can use the data inside the text, you will have to parse the JSON. After parsing, the data is an object or an array with objects on which you can operate: sort by price or relevance, count the number of results, and map different properties like product name, and description to the user interface.

  • How do I parse a JSON file?

How to parse a JSON file depends on the programming languages. The JSON standard is well-supported, and all modern programming languages do have either built-in support, or libraries that you can use to parse JSON. In the following sections, a basic example is given on how to convert JSON in different languages: JavaScript, PHP, Python, and Java. You’ll see that it works quite similarly in different languages.

  • Parsing JSON in JavaScript

JavaScript has a built-in functions JSON.parse and JSON.stringify to work with JSON. The following example demonstrates this, and also shows how to beautify JSON :

Now, JSON is a subset of JavaScript. It originates from JavaScript. So you can literally paste JSON data inside a JavaScript script, and it will be parsed into an object when you run the script. That can be handy when you have some static data in a web application. Since JSON is valid JavaScript, you can also parse JSON using the eval function, which allows dynamically executing JavaScript code. The eval function is generally considered unsafe though: it can be used to inject malicious code into a JavaScript application. So please don’t use eval, or if you do, take careful measures to prevent security risks. This approach is used in the json2.js library by Douglas Crockford (who “discovered” JSON): the library first validates whether there is no malicious code inside the JSON using a regular expression, and after that, it uses eval to parse the JSON.

  • Parsing JSON in PHP

PHP has built-in functions json_decode and json_encode to serialize JSON. You will probably need to do some post processing, since PHP allows either parses the data into objects, or in arrays.

  • Parsing JSON in Python

In Python, you can use the json library to work with JSON data. It comes with functions json.loads and json.dumps :

  • Parsing JSON in Java

In Java, there are various libraries available to work with JSON. A popular one is Jackson. Since Java is a strictly typed language, you normally need a data class on which you map your data. We will not write out an in-depth example but here is the gist of it:

  • How to use JSON parsing in practice?

In practice, you will often fetch data from a server, from disk, or from a database, and directly afterward parse it. This is often done in one go, by ready-made libraries. For example in plain JavaScript, you can use fetch :

Or you can use a library like Axios, in combination with TypeScript:

In short, most likely, the library that you use to fetch data will handle the parsing for you.

  • Is it difficult to parse JSON?

No. The JSON data format is very simple, which makes it quite straightforward to implement a parser for it. This is probably one of the reasons that JSON has become so popular: it’s easy to add support for it in any programming language. And also: it is a human-readable text format which makes it easy to have a look at the data without need to parse it. To parse data, you have to iterate over all bytes in the data one by one. When you encounter a [ character, you know it’s the start of an array. Then, if you encounter a digit, you collect all consecutive digits into a number, until you hit a comma or the end of the array ] . If you want to learn how to write a full JSON parser yourself, you can read the following in-depth tutorial: https://lihautan.com/json-parser-with-javascript . To give you an idea of what it is involved, here is the JavaScript code of a function which can parse JSON arrays and integer numbers:

Recent posts

  • Tabular-JSON: Combining the best of JSON and CSV
  • Smart JSON Formatting
  • Ad-free JSON Editor Online experience
  • How to write a streaming parser
  • JSON alternatives for data
  • Data-fetching
  • Specification
  • About: Jos de Jong
  • About: Indepth articles
  • Definitions
  • How to Buy XRP in 2024
  • How to Buy Bitcoin in 2024
  • How to Buy Shiba Inu in 2024
  • Crypto Gambling
  • Crypto Casinos
  • Crash Gambling
  • Crypto Sports Betting

Vangie Beal

JSON ( J ava S cript O bject N otation) is a lightweight data-interchange format that is easy for humans to read and write, and for machines to parse and generate.

In this definition...

What does JSON do?

JSON’s human-readable text transmits data objects consisting of attribute-value pairs and array data types. It was derived from JavaScript , but its language is independent. As a result, JSON makes Web services faster and more scalable by reducing request latency .

While JSON is based on the object notation of the JavaScript language, it does not require JavaScript to read or write because it is a text format that is language-independent. JSON’s notation contains these basic elements:

  • Objects: Objects begin and end with curly braces ({}).
  • Object Members: Members consist of strings and values, separated by colon (:). Members are separated by commas.
  • Arrays: Arrays begin and end with braces and contain values. Values are separated by commas.
  • Values: A value can be a string, a number, an object, an array, or the literals true, false or null.
  • Strings: Strings are surrounded by double quotes and contain Unicode characters or common backslash escapes.

While XML uses tags, JSON uses key-value pairs represented as “key”: “value”. Note that there must be a double quote before key and after value. It looks like: {“name” : “value”} . The curly braces denote an object, and name/value pairs are denoted by a name followed by a colon followed by a value, enclosed in quotes. So, in JSON {“name”: “Joe”} , Joe is a string, and a name is an object with one member called name .  

An array is represented as a square bracket [ ], where commas separate items within brackets. So, in JSON [“1”, “2”], 1 and 2 are numbers, and each number is separated from another number by a comma.

Go deeper into developing with JSON

Developer.com

How is JSON used?

JSON has evolved as an efficient data-interchange format with many use cases. It’s used to transfer data on Web Pages and NoSQL databases. Here are some of JSON’s most common use cases: 

Data transfer between systems

JSON is a useful format for transferring data between different applications and systems. It allows developers to serialize and deserialize data quickly and efficiently while preserving its original structure. This makes it very easy to share information between multiple parties who might have different coding languages and programming backgrounds.

Configuring data for applications

JSON can be used to configure data for applications. For example, suppose a developer has a database and wants their application to read from it and write back changes. In that case, they may do so by defining what type of data their application expects through configuration files written in JSON. 

Generating a JSON object from user-generated data 

Developers often want to save user input into their database when users fill out a website form to access it later as needed. They could develop custom code to handle each form field separately; however, there is a better option: they may generate JSON objects directly from form fields.

Storing metadata about entities in databases 

Metadata is simply data about data. For example, a database table can contain various information, including columns describing what type of entity each row represents, how many records there are in total, how many records have been added or deleted since last time, etc.

How is JSON used in Microsoft software development ?

Learn more at CodeGuru

Why was JSON created?

JSON was created as a lightweight format for exchanging data, particularly across applications and networks. As a result, it’s a fairly standard data transfer protocol that works well with most programming languages. It can be found in everything from APIs to webpages to video games. That’s because JSON is easy to read and write, making it ideal for both machines and humans alike. 

This data can be parsed by a JavaScript engine, making it ideal for transmitting hierarchical data structures or binary data over a network connection. JSON may also be used in situations where XML would be used, such as in RESTful APIs or JavaScript libraries. 

The official MIME media type for JSON is application/json. The filename extension is .json. Although JSON and JavaScript are loosely related, they are not identical. Data formatted according to JSON conventions can be manipulated directly by code written in any programming language that supports both JSON encoding and manipulation of basic data types. By contrast, arbitrary JavaScript code cannot manipulate JSON-formatted text directly; it must be converted into an intermediate representation compatible with whatever software environment is hosting the code. 

What did JSON replace? And is it better?

JSON was developed as an alternative to XML (Extensible Markup Language) for representing data in applications. It’s a lightweight format that’s easy to use and read and quickly becoming popular across web and mobile applications. JSON has several advantages over XML. Because the language adheres to JavaScript’s syntax, it’s easy for programmers to use both interchangeably in code, and it’s much easier to create a parser for JSON than XML; because of that, many developers are already familiar with how to read and write JSON documents. 

Most importantly, JSON’s files are smaller than XML and faster transmitting between servers. JSON data can be loaded quickly because its parsers are simpler, requiring less processing time and memory overhead.  XML is slower because it is designed for more than simply data interchange. Due to its simplicity, speed, and versatility, JSON has become popular in today’s development landscape.

The major advantage of working with JSON compared to XML is that it is shorter and easier to read. The human-readability aspect makes it easier for humans to understand their data structure when implemented as an object. This can save time if a developer debugs or tests their application or website. 

  • Server parsing: JSON’s easy to parse on both the client and server sides . It’s very lightweight on parsing, which means less memory usage on the developer’s server-side. 
  • JSON is faster: Since JSON is lightweight, it loads quickly. Developers don’t have to wait long before seeing anything on the screen while parsing large data. JSON is faster than XML because it is explicitly designed for data interchange. 
  • Schema support: Unlike XML, JSON doesn’t require any schema definition upfront. This means that devs don’t need to worry about defining a schema first before sending any data over HTTP requests. 
  • Language independent: Being language-independent means that developers can use JSON across different programming languages. For example, C# uses the Newtonsoft.Json package to handle JSON objects, whereas PHP has built-in support for handling JSON objects using the json_encode() function. 
  • Data sharing tool: Being lightweight and language-independent make it perfect for sharing data between different devices/applications over the internet without worrying about compatibility issues across different platforms and programming languages. 
  • Interoperable: JSON works well with all modern web browsers and mobile applications. So users can share data seamlessly between desktop and mobile apps by using JSON format.

Shortcomings

While JSON has many advantages, it also has some disadvantages. 

  • Cannot be used to store binary data: This means that if a developer wants to store a file in JSON format, they’ll need to convert it into a text-based format first (like Base64). 
  • Doesn’t support comments: It’s possible to create comments, but parsers will ignore those comments because they aren’t valid JSON syntax characters.

Examples of JSON in use

JSON’s code can be written in a variety of ways. For example, it can be written as a string or object. In either case, it must begin with { and end with }. The following examples show how to create a JSON string and a JSON object. The first example shows how to create a simple string with two key-value pairs. 

The second example shows how to add multiple key-value pairs within one set of curly braces. This is known as an object. Note that a comma must separate each key-value pair. Additionally, each key must be followed by : (colon) and its value. Finally, note that all values are enclosed in double-quotes.

The following syntax rules apply:

  • Data is in name/value pairs (for the first employee object: “FirstName” is the name and “Rose” is the value)
  • Data is separated by commas
  • Curly braces represent the JSON objects
  • Square brackets hold arrays

What is expected to replace JSON?

Although JSON has proven to be a popular data format and is unlikely to go away anytime soon, researchers and developers at MongoDB have found a way of further improving upon it. They call their creation BSON, short for binary JSON. It offers many of the same advantages as traditional JSON but with less overhead than its text-based counterpart. Other top JSON alternatives include:

YAML is a human-readable data serialization language. The acronym originally stood for YAML Ain’t Markup Language, but that initialism has since been dropped in favor of a backronym meaning YAML: Yet Another Markup Language. Its design goals include portability, ease of reading and writing, and interpretability by humans and computers. YAML can be used as a general-purpose data exchange format or as a way to store configuration files. 

Avro is a row-oriented remote procedure call and data serialization framework that runs on Apache Hadoop . It supports schema evolution and dynamic typing, which means developers can change their data structure without breaking clients that depend on it. This makes it easy to evolve schemas as their needs change over time. In addition, the schema is stored in JSON files, making it human-readable, editable, and portable across programming languages. 

MongoDB is a document-oriented database platform that uses JavaScript as its query language. MongoDB uses JSON-like documents with optional schemas and stores them in BSON, a binary representation of JSON. It supports server-side programming in multiple languages, including C++, Java, Perl, PHP, Python, and Ruby (JavaScript), and client-side programming in JavaScript (Node.js). 

Protocol buffers (or Protobufs) is an open-source, Google’s data interchange format. It allows the definition of structured data in a language-neutral form and efficient encoding and decoding of such definitions in many programming languages. Protobuf code can be compiled into a library or used directly in C++, Java, Python, Objective-C, Go, and C# code.

OData (Open Data Protocol) is a data access protocol that provides uniform data access to various types of data services. It includes both Web-based and service-oriented architectures capabilities. Because OData uses standard HTTP requests and responses, it is easy for developers to integrate with their existing systems, regardless of what platform or programming language they use.

This article was reviewed and updated in April 2022 by Aminu Abdullahi .

Vangie Beal

Vangie Beal is a freelance business and technology writer covering Internet technologies and online business since the late '90s.

  • ▼JSON Tutorial
  • Introduction
  • Online JSON viewer
  • Validate JSON with JSONLint
  • JSON Examples
  • PHP JSON installation and decode function
  • PHP JSON encode function
  • PHP JSON last error function
  • Working with JavaScript
  • Working with Python
  • JSONPath with JavaScript
  • JSONPath with PHP
  • Binary JSON - BSON

Structures of JSON

Description.

In this page you will learn about structures of JSON. you will also learn different forms of storing data in JSON.

Data Structures supported by JSON

JSON supports two widely used (amongst programming languages) data structures.

A collection of name/value pairs . Different programming languages support this data structure in different names. Like object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values . In various programming languages, it is called as array, vector, list, or sequence.

Since data structure supported by JSON is also supported by most of the modern programming languages, it makes JSON a very useful data-interchange format.

Data Types in JSON

JSON supports an array of data types. We will discuss those in detail in the following section of this page of the JSON tutorial.

Explanation of Syntax

An object starts and ends with '{' and '}'. Between them, a number of string value pairs can reside. String and value is separated by a ':' and if there are more than one string value pairs, they are separated by ','.

In JSON, objects can nest arrays (starts and ends with '[' and ']') within it. The following example shows that.

Explanation of Syntax:

An Array starts and ends with '[' and ']'. Between them, a number of values can reside. If there are more than one values reside, they are separated by ','.

If the JSON data describes an array, and each element of that array is an object.

Remember that even arrays can also be nested within an object. The following shows that.

A value can be a string, a number, an object, an Array, a Boolean value (i.e. true or false) or Null. This structure can be nested.

A string is a sequence of zero or more Unicode characters, enclosed by double quotes, using backslash escapes. A character is represented as a single character string, similar to a C or Java string.

The following table shows supported string types.

String Types Description
" A double quotation mark.
\ Reverse Solidus
/ Solidus
b Backspace
f form feed
n newline
r Carriage return
t Horizontal tab
u Four hexadecimal digits

The following table shows supported number types.

Number Types Description
Integer Positive or negative Digits.1-9. And 0.
Fraction Fractions like .8.
Exponent e, e+, e-, E, E+, E-

Whitespace can be placed between any pair of supported data-types.

Previous: JSON Tutorial Next: Online JSON viewer

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

Visualize JSON data with these popular tools

what is json representation

JSON is one of the most popular data structures in and out of web development and data handling because it’s straightforward, readable, flexible, and lightweight.

what is json representation

In contrast to other key-data structures and formats like YAML, JSON is easier to read and write and computer processors to parse and generate. Plus, JSON is based on key-value pairs, which are great for relations and representing complex data structures.

Everybody uses JSON on multiple career development paths. I have dabbled in data science, backend engineering smart contracts and DevOps, and I’ve had to use JSON data while working on each of these.

As you use JSON and your data set grows more nested and complex, you may want to visualize it for more scannability, debugging validation, and, sometimes, analysis. I will show you some great tools I use to visualize JSON data, and then I’ll talk about how to use them.

When you might want to visualize JSON data

You need to visualize JSON data in many situations and for many purposes. Let’s go over some of them.

Exploring and understanding complex JSON data structures

Your JSON data can become complex with size, especially when you have nested objects and arrays. You can visualize the JSON in a tree-like structure to explore hierarchy, expand/collapse nodes, and understand the data organization.

Validating JSON data

You can validate your JSON data and spot invalid data, syntax, incorrect nesting, etc. For this purpose, you can use linting tools like JSONLint or one on your IDE marketplace.

Debugging API responses

what is json representation

Over 200k developers use LogRocket to create better digital experiences

what is json representation

If you’re building or consuming APIs that return JSON data as a response, visualizing the data is quite helpful for understanding the structure and content, especially when the content is large or nested.

Presenting JSON data to stakeholders

Visualizing complex JSON data is excellent for sharing with people who may not be familiar with the technical aspects.

Mocking JSON data during development

When building applications that consume or use JSON, you’ll likely mock the data before the API is ready. Visualizing the mock data would help you ensure it matches your expected structure.

Popular tools for visualizing JSON data

You can use many tools to visualize JSON data in different environments, from IDEs to browsers and other apps.

JsonTree.js

JsonTree.js is a lightweight JavaScript library that helps with generating customizable tree views for visualizing JSON data. You’ll find JsonTree.js helpful if you want to manage and display hierarchical data structure clearly and interactively.

Features of JsonTree.js Here’s an non-exhaustive list of the features JSONTree provides:

  • Zero dependencies
  • CSS theme support
  • Custom rendering
  • Lightweight
  • TypeScript support and support for frameworks like React and Angular
  • Public API for interacting with the tree
  • Configurable DOM elements
  • Interactive features
  • Array paging support

Once you have NodeJS installed, you can run this command to install the jjsontree.js library and get started visualizing JSON data with it:

Now, you can add this CDN link to the HTML of your webpage to make the JSON visible:

Also, add the necessary CSS and JS files to your HTML:

Here’s how you can visualize three JSON trees in your webpage with JSONTree.js:

The HTML document sets up the webpage to display three different JSON Tree visualizations with the jsontree.js library.

You can check out the JSONTree.js documentation to learn how to customize this further to style, add more functionalities, and use more of the tool’s features.

JsonTree.js is quite versatile in this regard, and since it’s lightweight, it’s suitable for use in production and development.

JSON Hero is an advanced, feature-rich JSON visualization tool with an intuitive UI that anyone can pick up and use.

JSON Hero makes it easy to work with JSON files from various sources with a clean JSON viewer interface that supports all field types, from images to dates, colors, URLs, or videos.

You can upload or link to your JSON files, search through them with lightning speed, and collaborate with team members from JSON Hero:

Postman, Insomnia, and other API testing applications

API testing tools like Postman and Insomnia ship with tools you can use to visualize JSON for requests and responses.

You’ll find these useful if you’re debugging JSON or using JSON data for API development, collaborating with a team, or you need to document the JSON data since they also ship with these features.

IDE and text editor extensions

You’ll find an extension/plugin for working with and visualizing JSON in your tooling of choice’s extensions marketplace.

All you have to do is search and select one that matches the use case and features you need. Most extensions here help with linting JSON so you can view them better in your development environment. In some cases, they provide features for converting JSON to native language types like JSON to Python, Go, or Swift:

In some cases, your editor could be enough to visualize JSON data. JetBrains IDEs ship with great support for JSON and other file types.

When to use these tools

Visualizing JSON data with any of these tools boils down to what you’re trying to do and the environment in which you’re using JSON data.

Here’s a table with an overview of the pros and cons of using these tools and when to use any of them for the best experience possible:

Tool Pros Cons When to use
JsonTree.js Zero dependencies, lightweight, customizable, supports frameworks like React and Angular, interactive features, Array paging support Limited to browser environments, basic feature set compared to more advanced tools You need a lightweight, customizable tree view to visualize hierarchical JSON data
JSON Hero Intuitive UI supports various field types (images, dates, colors, etc.) and collaboration features It may require an internet connection and a more complex setup than simple libraries When you need an advanced, feature-rich JSON viewer with a clean interface and collaboration tools
Postman/Insomnia Comprehensive API testing features, collaboration and documentation tools, built-in JSON viewer Primarily designed for API testing, not dedicated JSON visualization When you’re debugging JSON, developing APIs, or needing to document and collaborate on JSON data
IDE/Text Editor Extensions Integrated with the development environment, linting and conversion features; no additional tools are needed Depending on the capabilities of the specific IDE or extension, may lack advanced visualization When you need basic JSON visualization and linting within your development environment

Challenges of visualizing data

JSON is quite simple and structured enough at first glance, but as the data grows and your use case becomes more critical, you’ll likely face some challenges with visualizing data.

Visual noise

When the dataset is large with depth and complexity, objects may appear similar on screen, making it hard to find or distinguish data. You can tackle visual noise by ensuring the data is clean, removing outliers, or using a listing tool to reduce the visual noise.

Performance issues

Processing and parsing extensive JSON data can be time-consuming and resource-intensive. You can implement data chunking or pagination to process and visualize data in smaller segments or use efficient data structures and algorithms to minimize memory usage and processing time.

Transforming data

Sometimes, it can be complex to transform nested JSON data into other formats. You can use data transformation tools like ETL (Extract, Transform, Load) processes or custom scripts to restructure and clean your data.

Interactivity

You should add interactive elements for an immersive experience with your JSON data. Some JSON visualization tools support visualizing data in different formats. To add interactivity, you can check out D3.js for JavaScript or Dash for Python .

The tools in this article help solve most of the challenges you may encounter when visualizing and interacting with JSON data.

You’ve learned about JSON and some popular tools you can use to visualize JSON data to elevate your tinkering experience. Explore these options, and select a tool based on the situation you are in with JSON.

LogRocket : Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #vanilla javascript

Would you be interested in joining LogRocket's developer community?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

what is json representation

Stop guessing about your digital experience with LogRocket

Recent posts:.

Provide Inject API Vue 3

Using provide / inject in Vue.js 3 with the Composition API

Learn how to use the provide/ inject function pair with the Composition API to pass data into deeply nested components in Vue.js 3.

what is json representation

Linting with Ruff: the Python linter built with Rust

Did you know that the efficiency of your linter can significantly affect your productivity? After adding a small feature to […]

what is json representation

Go long by generating PDFs in Golang with Maroto

Go, also known as Golang, is a statically typed, compiled programming language designed by Google. It combines the performance and […]

what is json representation

MobX adoption guide: Overview, examples, and alternatives

MobX is a lightweight, boilerplate-free state management library that offers a reactive approach to state management.

what is json representation

Leave a Reply Cancel reply

Dataset vs. Database

Even though datasets and databases sound similar and frequently used interchangeably, do you know that both entirely differ? 

Dataset and database represent two different concepts, and they have unique structures, purposes, and uses.

It is essential to distinguish between these terms to make effective decision-making in data management.

This blog will give you a detailed understanding of the datasets and databases, which will help you make informed decisions that align with your specific needs.

Dataset vs. Database- The Concept

What is a dataset.

A dataset is a collection of related data organized in a structured format, usually in tables or lists.

Datasets can be static or dynamic and can include numerical values, text, images, or audio recordings. They are typically used for research, data analysis, or machine learning projects.

They are stored in formats like CSV (Comma Separated Values), Excel spreadsheets, or JSON (JavaScript Object Notation) files.

What Is a Database?

A database is a structured collection of data stored and accessed electronically in a computer system. It allows the storage of vast amounts of data in a single space. 

Data may include text, numbers, images, or other types of data. A database’s structure is complex, involving tables, indexes, views, and procedures.

A database generally consists of multiple datasets, which are managed by Database Management Systems (DBMS) like MySQL and PostgreSQL. 

Dataset vs. Database- Types

Types of datasets.

Types of Datasets

Datasets are classified based on the structure, source, and intended use. Some of the primary types of datasets include:

  • Structured Datasets
  • Unstructured Datasets
  • Semi-Structured Datasets
  • Time-Series Datasets
  • Geospatial Datasets
  • Transactional Datasets

1. Structured Datasets

These are highly organized datasets, generally in tabular format with rows and columns. Each column represents a specific variable, and each row represents a record.

  • Relational Datasets – These are organized in tables with rows and columns, where each column represents a variable, and each row represents a single record.
  • CSV (Comma Separated Values) – In CSV format, each line of the file is a data record, and each record has one or more fields, separated by commas. 

2. Unstructured Datasets

These datasets do not have a pre-defined format or structure. They consist of text, images, videos, or other multimedia files that do not fit into a rigid framework.

  • Text Data – This includes datasets that consist of plain text like books, articles, or social media posts. 
  • Media Files – They are composed of images, audio files, and videos and require specific processing techniques, such as computer vision, to extract data. 

3. Semi-Structured Datasets

These are the datasets that are not as organized as structured datasets but consist of tags or other markers to separate data elements like XML, JSON, or HTML files.

  • XML (eXtensible Markup Language) – Data is stored in a tree-like structure within tags. It stores both hierarchical and textual data in a way that is machine—and human-readable.
  • JSON (JavaScript Object Notation) – Data is structured in key/value pairs. Due to its compatibility with other programming languages, JSON is generally used for APIs and web services.

4. Time-Series Datasets

These datasets contain sequences of data points collected over time intervals, tracking variables such as temperature, stock prices, or sales data.

5.  Geospatial Datasets

These datasets include spatial coordinates and other geographic information and are used in GIS (Geographic Information Systems) for mapping patterns over geographical areas.

6.  Transactional Datasets

These datasets consist of records of transactions like purchases or sales that are characterized by time stamps, amounts, and identifiers and are typically used in the retail and banking sectors.

Types of Database

Types of Database

There are different types of databases, each serving a different purpose. Some of the major types of databases include:

  • Relational Databases (RDBMS)
  • NoSQL Databases
  • Object-Oriented Databases
  • In-Memory Databases (IMDB)
  • Time Series Databases (TSDB)
  • NewSQL Databases
  • Distributed Databases

1. Relational Databases (RDBMS)

In this type of database, data is stored in structured format within tables using a structured query language (SQL). Foreign keys define the relationships between tables.

2. NoSQL Databases

Unlike relational databases, these are more flexible and designed for specific data models. They do not need  fixed table schemas and  are categorized into several types:

  • Document Stores — The data is stored in documents like JSON and BSON, which are grouped into collections, such as MongoDB and CouchDB.
  • Key-Value Stores — This type of data store stores data as a collection of key-value pairs. It is helpful for simple queries, such as Redis or DynamoDB.
  • Wide-Column Stores – Data is stored in columns instead of rows. This makes it efficient for querying large datasets. For example: Cassandra, HBase.
  • Graph Databases —These are designed to store and navigate relationships for interconnected data, such as social networks or recommendation engines. Examples include Neo4j and ArangoDB.

3. Object-Oriented Databases

These are databases that store data in the form of objects and are useful for applications developed with object-oriented programming languages, such as db4o and ObjectDB.

4. In-Memory Databases (IMDB)

These databases store the data in the computer’s main memory(RAM) instead of on disk. This speeds up data processing tasks and can be used for applications requiring real-time data processing, such as Redis and SAP HANA.

5. Time Series Databases (TSDB)

This type of database specializes in handling time-series or time-stamped data. It is apt for IoT, financial services, and monitoring applications that measure change over time. For example, InfluxDB and TimescaleDB.

6. NewSQL Databases

These databases provide the same scalable performance of NoSQL systems for online transaction processing (OLTP), combining the ACID (Atomicity, Consistency, Isolation, Durability). For example, Google Spanner and CockroachDB.

7. Distributed Databases

These databases are distributed across multiple physical locations but are connected through a network and function as a single database system. Examples are Cassandra and Couchbase.

Dataset vs. Database- Examples

Dataset example.

An example of a dataset is Starbucks’ locations in the United States . In this dataset, information like store name, address, city, coordinates, and operating hours are included. 

Database Example

An example of a database is the United States Census Bureau database . It offers data related to population demographics, economic activities, and housing statistics, which helps in planning, policy-making, and research.

Dataset vs. Database-similarities and differences

Similarities.

Listed are 4 significant similarities that are found both in the dataset and database:

  • Data Storage
  • Data Analysis
  • Querying Capability

1. Data Storage

Both datasets and databases store data and serve as repositories where information is organized, accessed, and managed. 

2. Data Analysis

Datasets and databases are essential tools in data analysis. Analysts use both to extract insights, perform statistical analysis, and support decision-making processes.

3. Structure

Both datasets and databases have structured formats. For example, data is organized in tables, columns, and rows in a relational database, which is similar to a structured dataset.

4. Querying Capability

Specific data is retrieved through versatile querying mechanisms in both datasets and databases. 

For databases, SQL (Structured Query Language) is commonly used, while structured datasets apply similar query techniques, showcasing the adaptability and flexibility of these tools. 

Similarities between Datasets and Databases

Data Storage Both are used to store and organize data in repositories.
Data Analysis Both are essential tools for extracting insights and data analysis.
Structure Both can have structured formats, such as tables with rows and columns.
Querying Capability    Both allow for the retrieval of specific data through querying mechanisms.

Differences

Here are 4 differences between datasets and databases:

  • Data Integrity and Types
  • Scalability and Concurrency
  • Data Manipulation

1. Structure

Datasets adopt a flat or tabular structure similar to spreadsheets, while databases are more complex and store data in various formats.

2. Data Integrity and Types

Databases, with their enforcement of data types and rules, ensure data accuracy and consistency. 

However, datasets, with their flexibility and ability to contain various types of data such as numbers and text, empower users with a wide range of possibilities.

3. Scalability and Concurrency

Databases enhance system resources and distribute data across multiple servers, supporting high levels of concurrency. 

On the other hand, datasets have limited scalability and are not optimized for concurrency.

4. Data Manipulation

Databases have extensive data manipulation capabilities and advanced querying functionalities.

In contrast, datasets are limited to basic manipulations like simple computations.

If you are interested in knowing more about data manipulation libraries useful for web scraping, then you can read our article on ‘ Data Manipulation Libraries in Python ‘.

Differences between Datasets and Databases

Structure Flat or tabular structure similar to spreadsheets. Complex structures including relational models and non-relational models like documents, graphs, and key-value pairs.
Data Integrity and Types Focus on data quality with diverse data types; no strict enforcement of schemas. Enforce strict data types and schemas, maintaining integrity through constraints and transaction management.
Scalability and Concurrency Limited scalability; not optimized for concurrency. Designed to scale vertically and horizontally; supports high concurrency with advanced transaction management and locking mechanisms.
Data Manipulation Limited to reading, filtering, and basic operations. Extensive manipulation capabilities with CRUD operations and advanced querying functionalities.

Do you know that, apart from databases, you also have standard and efficient ways of storing and managing scraped data? 

Read our article on ‘ Storage and Management of Scraped Data With Python ’ to find out more.

Dataset vs. Database: Which To Choose?

Choosing datasets or databases depends on your specific needs. 

If you want something ideal for managing relatively small, static data for your analysis, exploration, or visualization, then go for datasets.

Datasets are simple to set up and can be used, especially when the data structure is flat and tabular. They also facilitate easy sharing and integration across various environments. 

But if you are looking for something that can handle large volumes of data and requires robust management, you can choose databases. 

Databases ensure data integrity and support concurrent access by multiple users or applications. They also provide robust querying and reporting capabilities. 

ScrapeHero Data Store

Home page of ScrapeHero Data Store

ScrapeHero provides ready-to-purchase datasets generated by monitoring thousands of brands globally. These datasets are suitable for conducting competitive analysis and crafting informed business strategies.

From the ScrapeHero data store , you can instantly download accurate, updated, affordable, and ready-to-use retail store location data for your business needs.

Our datasets are updated monthly and undergo multiple rounds of automated and manual checks in order to maintain the highest level of quality within the affordable price range.

We also provide historical statistics on location data, including store openings, closures, etc., for most brands.

If you are a regular subscriber rather than buying every quarter, you can even get steep discounts with a yearly subscription.

In addition, we can offer you custom data enrichment services for most of our POI datasets. 

But we suggest you choose a complete web scraping service from us. 

ScrapeHero web scraping service

ScrapeHero’s web scraping service is one of the most sought-after scraping services. We specialize in building custom solutions for our customers.

Our advanced web scraping infrastructure can support large-scale data extraction and deal with complex scraping problems effectively. 

Transparency in interactions, high data quality, and timely service delivery are the reasons why we are able to maintain a 98% customer retention rate.

Wrapping Up

Understanding the differences between a database and a dataset is extremely important to choose the right tool and approach for your specific data-related tasks.

ScrapeHero can help you overcome all the challenges that come across data extraction and provide you with the data you need for further analysis. 

Frequently Asked Questions

Data is raw, unorganized facts, whereas a dataset is a collection of organized data for a specific purpose.

A dataset is a collection of structured data, usually in tabular form. On the other hand, a data source is the origin from where data is collected and may have one or more datasets. 

A database is a collection of structured data which is stored in a computer system. It consists of one or more data tables.  A data table is a single arrangement of data within a database, usually in rows and columns.

You can use the pandas library to create a dataset by defining a DataFrame.  For example, import pandas as pd; data = {‘Name’: [‘John’, ‘Anna’], ‘Age’: [28, 22]}; df = pd.DataFrame(data) creates a dataset with names and ages.

We can help with your data or automation needs

Turn the Internet into meaningful, structured and usable data

Continue Reading ..

Nicole Leinbach-Reyhle at Forbes recently wrote an article comparing Etsy and Amazon in the "handmade" category. It explored the foray of Amazon into this category where Etsy has been the dominant player. When Amazon tries…

Web scraping is the best method to gather product data from Amazon. Scraping tools such as Data scraper help users to scrape eCommerce websites easily. Here we'll show you how to extract data from Amazon.com…

The India eCommerce market is going through a lot of growth. A largely untapped market due to the lack of infrastructure - logistics, electronic payments, shipping and cultural opposition to eCommerce has seen a huge…

Posted in:   Featured , Web Scraping Tutorials

Published On:   August 27, 2024

Turn the Internet into meaningful, structured and usable data   

Contact Sales below or call +1 617 297 8737

Please let us know how we can help you and we will get back to you within hours

ScrapeHero Logo

Can we help you get some data?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How do you represent a JSON array of strings?

This is all you need for valid JSON, right?

finneycanhelp's user avatar

  • 13 That's a JSON array containing two strings, yes... is there more to that question? ;) –  Town Commented Mar 14, 2011 at 0:39
  • I read something which contradicted what we're all agreeing on. So, I wanted the reality check there. Thanks! –  finneycanhelp Commented Mar 14, 2011 at 1:18
  • 4 Ah, I see! It's a shame you can't accept your own question as the answer :D –  Town Commented Mar 14, 2011 at 10:30
  • :) Well, it's not just the answers that's fun. It's great people such as yourself that help make this site a fun success! –  finneycanhelp Commented Mar 16, 2011 at 2:06

4 Answers 4

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference .

A valid JSON always starts with either curly braces { or square brackets [ , nothing else.

{ will start an object :

Hint : although javascript accepts single quotes ' , JSON only takes double ones " .

[ will start an array :

Hint : spaces among elements are always ignored by any JSON parser.

And value is an object , array , string , number , bool or null :

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed .

Here are a few extra valid JSON examples, one per block:

Community's user avatar

  • 1 Does JSON have to have double quotes? I tried to validate the OP's string above but with single quotes on jsonlint.com and it tells me it is invalid. But it's valid when using double quotes. –  Ray Commented Sep 13, 2016 at 13:50
  • @Ray as usual, that doesn't have a simple yes or no answer, although I'd say it's mostly "yeah, just go with double quotes". json.org tells us only about using double quotes, and most places will probably follow that. However, here's a deeper investigation about it: stackoverflow.com/a/2275428/274502 –  cregox Commented Sep 14, 2016 at 22:17
  • Improve images for SO's dark theme, please. –  carloswm85 Commented Aug 27, 2020 at 11:14
  • @carloswm85 i'll leave it to you! feel free to edit the answer. 😘 (i don't own a desktop, don't know where to set the dark theme, and don't really care... 😏) –  cregox Commented Aug 28, 2020 at 12:22

Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:

then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and "somestring2" .

Drilon Kurti's user avatar

  • 14 The code example you posted is invalid, when you would try to parse that string as a json it'll throw an error/exception. The fact you say that JSON is always key/value pairs is also inherently wrong. Nothing in the JSON spec says you NEED to have key/value pairs. When talking about data transport indeed key/value pairs are the most useful structure but the string the OP posted is perfectly valid JSON: codebeautify.org/jsonviewer/92ac7b –  ChrisR Commented May 7, 2014 at 9:28
  • 1 I had API's on the brain, where you want to look up the value in an array based on a key. So it would be, for an un-named array, {"1":"somestring1", "2":"somestring2"} –  PapaSmurf Commented Aug 10, 2014 at 23:27

Basically yes, JSON is just a javascript literal representation of your value so what you said is correct.

You can find a pretty clear and good explanation of JSON notation on http://json.org/

ChrisR's user avatar

This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to @cregox ...

A bit complicated but can explain a lot in a single JSON string.

Ankur  Jyoti Phukan's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged json or ask your own question .

  • The Overflow Blog
  • LLMs evolve quickly. Their underlying architecture, not so much.
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Immutability across programming languages
  • What is LED starter?
  • Sources for Raba bar bar Hana legends explanations
  • How to assess whether it is imposter syndrome or actual low quality work during Ph.D.?
  • Can You Replace an Aberrant Mind Sorcerer Spell with a Spell and Learn the Replaced Spell as a Standard Sorcerer Spell During the Same Level-Up
  • Need strftime() output in the buffer
  • Resonance structure of aromatic [S4N4]2+
  • Solve an equation perturbatively
  • Where did Geordi's eyes go?
  • Is there any video of an air-to-air missile shooting down an aircraft?
  • Is 2'6" within the size constraints of small, and what would the weight of a fairy that size be?
  • What was I thinking when I made this grid?
  • Reduce String Length With Thread Safety & Concurrency
  • using a tikz foreach loop inside a newcommand
  • If physics can be reduced to mathematics (and thus to logic), does this mean that (physical) causation is ultimately reducible to implication?
  • Inconsistent “unzip -l … | grep -q …” results with pipefail
  • "can-do" vs. "can-explain" fallacy
  • Opamp Input Noise Source?
  • Why are volumes of revolution typically taught in Calculus 2 and not Calculus 3?
  • Why do we reduce a body to its center of mass when calculating gain/loss of gravitational potential energy?
  • Interpretation of the ideal gas single particle partition function
  • Please help me to identify specific house plant
  • Did US troops insist on segregation in British pubs?
  • Antenna speed: slow and fast tracking( explanation of a parameter in comparison table)

what is json representation

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, json array literals.

This is a JSON string:

Inside the JSON string there is a JSON array literal:

Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean or null .

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

JavaScript Arrays

Accessing array values.

You access array values by index:

Arrays in Objects

Objects can contain arrays:

Advertisement

Looping Through an Array

You can access array values by using a for in loop:

Or you can use a for loop:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. SQL Server JSON: Comprehensive Guide. Introduction to JSON

    what is json representation

  2. JSON Tutorial

    what is json representation

  3. JSON Objects Explained!

    what is json representation

  4. JSON Objects Explained!

    what is json representation

  5. JSON representation of an artist in Spotify

    what is json representation

  6. JSON

    what is json representation

COMMENTS

  1. JSON

    JSON ( JavaScript Object Notation, pronounced / ˈdʒeɪsən / or / ˈdʒeɪˌsɒn /) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays (or other serializable values).

  2. What Is JSON and How Do You Use It?

    JSON is a text-based data representation format that can encode six different data types. JSON has become a staple of the software development ecosystem; it's supported by all major programming languages and has become the default choice for most REST APIs developed over the past couple of decade.

  3. What is JSON

    JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page. JSON is "self-describing" and easy to understand. JSON Example. This example defines an employees object: an array of 3 employee records (objects):

  4. JSON for Beginners

    JSON ( J ava S cript O bject N otation) is a text-based data exchange format. It is a collection of key-value pairs where the key must be a string type, and the value can be of any of the following types: A couple of important rules to note: In the JSON data format, the keys must be enclosed in double quotes.

  5. Working with JSON

    JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

  6. JSON Introduction

    JSON is a lightweight data-interchange format. JSON is plain text written in JavaScript object notation. JSON is used to send data between computers. JSON is language independent *. *. The JSON syntax is derived from JavaScript object notation, but the JSON format is text only. Code for reading and generating JSON exists in many programming ...

  7. A beginner's guide to JSON, the data format for the internet

    JSON.parse(string) takes a string of valid JSON and returns a JavaScript object. For example, it can be called on the body of an API response to give you a usable object. The inverse of this function is JSON.stringify(object) which takes a JavaScript object and returns a string of JSON, which can then be transmitted in an API request or response.

  8. What is JSON and what is it used for?

    JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript. An example of where this is used is web services responses.

  9. JSON

    JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. JSON is built on two structures: A collection of name/value pairs.

  10. What Is JSON?

    JSON, which stands for "JavaScript Object Notation," is a lightweight, text-based data exchange format that both humans and machines can write and read. Its simplicity and ease of use make it one of the most common formats for transferring data between a server and client—or between different parts of an application.

  11. JSON Tutorial

    JSON Tutorial. JSON stands for JavaScript Object Notation is a lightweight and human-readable format for storing and exchanging data. It is a format for structuring data. This format is used by different web applications to communicate with each other. It has become the actual standard for data communication across web applications due to its ...

  12. What is JSON? The universal data format

    JSON is the leading data interchange format for web applications and more. ... That is the built-in mechanism for JavaScript programs to take an in-memory object representation and turn it into a ...

  13. What is JSON

    JSON, short for JavaScript Object Notation, is a lightweight data-interchange format used for transmitting and storing data. It has become a standard format for web-based APIs due to its simplicity and ease of use. ... Data Representation: JSON represents data in key-value pairs. Each key is a string enclosed in double quotes, followed by a ...

  14. JSON methods, toJSON

    The JSON (JavaScript Object Notation) is a general format to represent values and objects. It is described as in RFC 4627 standard. Initially it was made for JavaScript, but many other languages have libraries to handle it as well. ... The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object. We are ...

  15. JSON Explained

    JSON, or JavaScript Object Notation, is a very common data interchange format. This in-depth guide explains all there's to know about JSON! ... They are used to represent associative arrays and are separated by commas and enclosed in curly brackets. The fifth category is Booleans. Boolean data represents true or false values. The sixth category ...

  16. Parse JSON: What is JSON parsing and how does it work?

    Now, JSON is a subset of JavaScript. It originates from JavaScript. So you can literally paste JSON data inside a JavaScript script, and it will be parsed into an object when you run the script. That can be handy when you have some static data in a web application. Since JSON is valid JavaScript, you can also parse JSON using the eval function ...

  17. What is JSON?

    MongoDB uses JSON-like documents with optional schemas and stores them in BSON, a binary representation of JSON. It supports server-side programming in multiple languages, including C++, Java, Perl, PHP, Python, and Ruby (JavaScript), and client-side programming in JavaScript (Node.js).

  18. JSON Structures

    JSON supports two widely used (amongst programming languages) data structures. A collection of name/value pairs. Different programming languages support this data structure in different names. Like object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values.

  19. Visualize JSON data with these popular tools

    JSON is one of the most popular data structures in and out of web development and data handling because it's straightforward, readable, flexible, and lightweight. In contrast to other key-data structures and formats like YAML, JSON is easier to read and write and computer processors to parse and generate. Plus, JSON is based on key-value ...

  20. JSON Syntax

    JSON Syntax Rules. JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs. Data is separated by commas. Curly braces hold objects. Square brackets hold arrays.

  21. Dataset vs. Database-A Comprehensive Guide

    Dataset and database represent two different concepts, and they have unique structures, purposes, and uses. ... JSON is generally used for APIs and web services. 4. Time-Series Datasets. These datasets contain sequences of data points collected over time intervals, tracking variables such as temperature, stock prices, or sales data. ...

  22. How do you represent a JSON array of strings?

    108. Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary: { "MyStringArray" : ["somestring1", "somestring2"] } then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and ...

  23. JSON Arrays

    Inside the JSON string there is a JSON array literal: Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.