- JSON
- Description
- JavaScript and JSON differences
- Full JSON grammar
- Static properties
- Static methods
- Examples
- Example JSON
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How To Work with JSON in JavaScript
- JSON Format
- Comparison to JavaScript Object
- Accessing JSON Data
- Functions for Working with JSON
- JSON.stringify()
- JSON.parse()
- Conclusion
- Tutorial Series: How To Code in JavaScript
JSON
The JSON namespace object contains static methods for parsing values from and converting values to JavaScript Object Notation (JSON).
Description
Unlike most global objects, JSON is not a constructor. You cannot use it with the new operator or invoke the JSON object as a function. All properties and methods of JSON are static (just like the Math object).
JavaScript and JSON differences
JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null . It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is not JSON. For example:
Property names must be double-quoted strings; trailing commas are forbidden.
Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported.
Any JSON text is a valid JavaScript expression, but only after the JSON superset revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a SyntaxError .
Other differences include allowing only double-quoted strings and no support for undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML.
The same text may represent different values in JavaScript object literals vs. JSON as well. For more information, see Object literal syntax vs. JSON.
Full JSON grammar
Valid JSON syntax is formally defined by the following grammar, expressed in ABNF, and copied from IETF JSON standard (RFC):
JSON-text = object / array begin-array = ws %x5B ws ; [ left square bracket begin-object = ws %x7B ws ; < left curly bracket end-array = ws %x5D ws ; ] right square bracket end-object = ws %x7D ws ; >right curly bracket name-separator = ws %x3A ws ; : colon value-separator = ws %x2C ws ; , comma ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return ) value = false / null / true / object / array / number / string false = %x66.61.6c.73.65 ; false null = %x6e.75.6c.6c ; null true = %x74.72.75.65 ; true object = begin-object [ member *( value-separator member ) ] end-object member = string name-separator value array = begin-array [ value *( value-separator value ) ] end-array number = [ minus ] int [ frac ] [ exp ] decimal-point = %x2E ; . digit1-9 = %x31-39 ; 1-9 e = %x65 / %x45 ; e E exp = e [ minus / plus ] 1*DIGIT frac = decimal-point 1*DIGIT int = zero / ( digit1-9 *DIGIT ) minus = %x2D ; - plus = %x2B ; + zero = %x30 ; 0 string = quotation-mark *char quotation-mark char = unescaped / escape ( %x22 / ; " quotation mark U+0022 %x5C / ; \ reverse solidus U+005C %x2F / ; / solidus U+002F %x62 / ; b backspace U+0008 %x66 / ; f form feed U+000C %x6E / ; n line feed U+000A %x72 / ; r carriage return U+000D %x74 / ; t tab U+0009 %x75 4HEXDIG ) ; uXXXX U+XXXX escape = %x5C ; \ quotation-mark = %x22 ; " unescaped = %x20-21 / %x23-5B / %x5D-10FFFF HEXDIG = DIGIT / %x41-46 / %x61-66 ; 0-9, A-F, or a-f ; HEXDIG equivalent to HEXDIG rule in [RFC5234] DIGIT = %x30-39 ; 0-9 ; DIGIT equivalent to DIGIT rule in [RFC5234]
Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.
Static properties
The initial value of the @@toStringTag property is the string «JSON» . This property is used in Object.prototype.toString() .
Static methods
Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
Examples
Example JSON
"browsers": "firefox": "name": "Firefox", "pref_url": "about:config", "releases": "1": "release_date": "2004-11-09", "status": "retired", "engine": "Gecko", "engine_version": "1.7" > > > > >
You can use the JSON.parse() method to convert the above JSON string into a JavaScript object:
const jsonText = ` < "browsers": < "firefox": < "name": "Firefox", "pref_url": "about:config", "releases": < "1": < "release_date": "2004-11-09", "status": "retired", "engine": "Gecko", "engine_version": "1.7" >> > > >`; console.log(JSON.parse(jsonText));
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 24, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How To Work with JSON in JavaScript
Because JSON is derived from the JavaScript programming language, it is a natural choice to use as a data format in JavaScript. JSON, short for JavaScript Object Notation, is usually pronounced like the name “Jason.”
To learn more about JSON in general terms, read the “An Introduction to JSON” tutorial.
To begin thinking about where you may use JSON in your JavaScript programs, some general use cases of JSON include:
- Storing data
- Generating data structures from user input
- Transferring data from server to client, client to server, and server to server
- Configuring and verifying data
This tutorial will provide you with an introduction to working with JSON in JavaScript. To make the most use of this introduction, you should have some familiarity with the JavaScript programming language.
JSON Format
JSON’s format is derived from JavaScript object syntax, but it is entirely text-based. It is a key-value data format that is typically rendered in curly braces.
When you’re working with JSON, you’ll likely see JSON objects in a .json file, but they can also exist as a JSON object or string within the context of a program. Read more about the syntax and structure here.
When you’re working with a .json file, it will look like this:
"first_name" : "Sammy", "last_name" : "Shark", "online" : true >
If, instead, you have a JSON object in a .js or .html file, you’ll likely see it set to a variable:
var sammy = "first_name" : "Sammy", "last_name" : "Shark", "online" : true >
Additionally, you may see JSON as a string rather than an object within the context of a JavaScript program file or script. In this case, you may also see it all on one line:
Converting JSON objects into strings can be particularly useful for transporting data in a quick manner.
We’ve gone over the general format of JSON and how you may expect to see it as a .json file, or within JavaScript as an object or a string.
Comparison to JavaScript Object
It is worth keeping in mind that JSON was developed to be used by any programming language, while JavaScript objects can only be worked with directly through the JavaScript programming language.
In terms of syntax, JavaScript objects are similar to JSON, but the keys in JavaScript objects are not strings in quotes. Also, JavaScript objects are less limited in terms of types passed to values, so they can use functions as values.
Let’s look at an example of a JavaScript object of the website user Sammy Shark who is currently online.
var user = first_name: "Sammy", last_name : "Shark", online : true, full_name : function() return this.first_name + " " + this.last_name; > >;
This will look very familiar to you as a JSON object, but there are no quotes around any of the keys ( first_name , last_name , online , or full_name ), and there is a function value in the last line.
If we want to access the data in the JavaScript object above, we could use dot notation to call user.first_name; and get a string, but if we want to access the full name, we would need to do so by calling user.full_name(); because it is a function.
JavaScript objects can only exist within the JavaScript language, so when you’re working with data that needs to be accessed by various languages, it is best to opt for JSON.
Accessing JSON Data
JSON data is normally accessed in Javascript through dot notation. To understand how this works, let’s consider the JSON object sammy :
var sammy = "first_name" : "Sammy", "last_name" : "Shark", "online" : true >
In order to access any of the values, we’ll be using dot notation that looks like this:
sammy.first_name sammy.last_name sammy.online
The variable sammy is first, followed by a dot, followed by the key to be accessed.
To create a JavaScript alert that shows us the value associated with the key first_name in a pop-up, we can do so by calling the JavaScript alert() function:
Here, we’ve successfully called the value associated with the first_name key from the sammy JSON object.
We can also use square bracket syntax to access data from JSON. To do that, we would keep the key in double quotes within square brackets. For our sammy variable above, using square bracket syntax in an alert() function looks like this:
When you’re working with nested array elements, you should call the number of the item in your array. Let’s consider the JSON below:
var user_profile = "username" : "SammyShark", "social_media" : [ "description" : "twitter", "link" : "https://twitter.com/digitalocean" >, "description" : "facebook", "link" : "https://www.facebook.com/DigitalOceanCloudHosting" >, "description" : "github", "link" : "https://github.com/digitalocean" > ] >
To access the string facebook , we can call that item in the array within the context of dot notation:
alert(user_profile.social_media[1].description);
Notice that for each nested element we’ll use an additional dot.
Using dot notation or square bracket syntax allows us to access the data contained in JSON format.
Functions for Working with JSON
This section will look at two methods for stringifying and parsing JSON. Being able to convert JSON from object to string and vice versa is useful for transferring and storing data.
JSON.stringify()
The JSON.stringify() function converts an object to a JSON string.
Strings are useful for transporting data from a client to a server through storing or passing information in a lightweight way. For example, you may gather a user’s settings on the client side and then send them to a server. Later, you can then read the information with the JSON.parse() method and work with the data as needed.
We’ll look at a JSON object that we assign to the variable obj , and then we’ll convert it using JSON.stringify() by passing obj to the function. We can assign this string to the variable s :
var obj = "first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"> var s = JSON.stringify(obj)
Now, if we work with s , we’ll have the JSON available to us as a string rather than an object.
The JSON.stringify() function lets us convert objects to strings. To do the opposite, we’ll look at the JSON.parse() function.
JSON.parse()
Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side. We can do this using the JSON.parse() function.
To convert the example in the JSON.stringify() section above, we would pass the string s to the function, and assign it to a new variable:
Then, we would have the object o to work with, which would be identical to the object obj .
To take a deeper look, let’s consider an example of JSON.parse() within the context of an HTML file:
DOCTYPE html> html> body> p id="user">p> script> var s = ''; var obj = JSON.parse(s); document.getElementById("user").innerHTML = "Name: " + obj.first_name + " " + obj.last_name + "
" + "Location: " + obj.location; script> body> html>
OutputName: Sammy Shark Location: Ocean
Within the context of an HTML file, we can see how the JSON string s is converted to an object that is retrievable on the final rendering of the page by accessing the JSON via dot notation.
JSON.parse() is a secure function to parse JSON strings and convert them to objects.
Conclusion
JSON is a natural format to use in JavaScript and has many implementations available for use in many popular programming languages. If you want to use the format in another progamming language, you can see full language support on the “Introducing JSON” site.
Because it is lightweight and is readily transferred between programming languages and systems, JSON has been experiencing increased support in APIs, including the Twitter API.
You likely won’t be creating your own .json files but procuring them from other sources. You can check out these resources to learn about converting other data structures to JSON.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in JavaScript
JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.