JavaScript Object Notation (JSON) is a text format for the serialization of structured data. It is derived from the object literals of JavaScriptJSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
JSON Simple Object Examples
This is a JSON object with properties:{
"myObject":
{
"name":"obi wan kenobi",
"weapons":"lightsaber",
"specialPowers":"the force"
}
}
[/code
[code lang="js"]
This is a JSON object which contains
{
"Africa":{
}
JSON Simple Array Examples
This is a JSON Object containing a JSON array:{
"myObject":
{
"name":"obi wan kenobi",
"weapons": ["lightsaber","smoke grenade","knife","jedi things"],
"specialPowers":"the force"
}
}
This is a JSON array containing two objects:
{
"africaLagos": [
{
"from": -377711769600000,
"to": -1588464816000,
"dst": false,
"offset": 816,
"name": "LMT"
},
{
"from": -1588464816000,
"to": 253402300799000,
"dst": false,
"offset": 3600,
"name": "WAT"
}
]
}
More JSON Examples
Some tips working with JSON:
- Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data.
- Object literal names MUST be lowercase (ie – null, false, true etc).
- Keep all name and value pairs in quotes to aviod
- Validate your JSON before using it – http://www.jsonlint.com
- The default unicode encoding for JSON is UTF-8 (see all Application Media Types http://www.iana.org/assignments/media-types/application/index.html)
- The MIME media type for JSON text is application/json (type and subtype respectively). further reading: Multipurpose Internet Mail Extensions (MIME) http://en.wikipedia.org/wiki/MIME
Parsing JSON in
It’s not recommended to blindly evaluate any JSON string with eval() because of the security implications. It’s best if you use the JSON.parse() method, which is part of the language since ES5 and is natively provided by the Javascript engines in modern browsers. In jQuery, there’s the parseJSON() method:// an input JSON string
var jstr = '{"mykey": "my value"}';
var data = jQuery.parseJSON(jstr);
console.log(data.mykey); // "my value"
The opposite of JSON.parse() method is JSON.stringify(). It takes any object or array (or a primitive) and serializes it into a JSON string.
var dog = {
name: "Fido",
dob: new Date(),
legs: [1, 2, 3, 4]
};
var jsonstr = JSON.stringify(dog);
// jsonstr is now:
// {"name":"Fido","dob":"2010-04-11T22:36:22.436Z","legs":[1,2,3,4]}
Characters that must be escaped in JSON strings
- quotation mark “
- forward slash /
- back slash \
- new line n
- carriage return r
- tab t
Frequently Asked Questions (FAQs) about JSON Syntax and Tips
What is the significance of whitespace in JSON?
In JSON, whitespace is generally insignificant. It can be used for formatting and readability, but it does not impact the data structure or the data itself. This means you can add spaces, line breaks, or tabs to make your JSON data more readable without changing its meaning or functionality. However, it’s important to note that excessive use of whitespace can increase the size of the JSON file, which may affect loading times and performance.
How is JSON handled in JavaScript?
JSON is a native data format in JavaScript. It can be easily parsed and manipulated using built-in JavaScript methods. The JSON.parse()
method is used to convert a JSON string into a JavaScript object, while the JSON.stringify()
method is used to convert a JavaScript object into a JSON string. These methods make it easy to work with JSON data in JavaScript.
What are some common errors in JSON syntax?
Some common errors in JSON syntax include missing or extra commas, missing or extra quotation marks, and incorrect bracket pairing. JSON is very strict about its syntax. For example, all keys must be strings and must be enclosed in double quotes. Also, all items in an array or object must be separated by commas, but there should not be a comma after the last item.
How can I convert JSON to other formats?
There are many tools and libraries available for converting JSON to other formats, such as XML, CSV, or HTML. The specific method will depend on the programming language you are using and the format you want to convert to. For example, in JavaScript, you can use the JSON.parse()
method to convert JSON to a JavaScript object, which can then be manipulated and converted to other formats.
Does the order of keys matter in JSON?
No, the order of keys in a JSON object does not matter. JSON objects are an unordered collection of key-value pairs. This means that { "name": "John", "age": 30 }
is the same as { "age": 30, "name": "John" }
. However, when working with arrays in JSON, the order of elements does matter.
How can I validate my JSON data?
There are many online tools available for validating JSON data, such as JSONLint. These tools can check your JSON data for syntax errors and formatting issues. In addition, many programming languages have built-in functions or libraries for validating JSON data.
Can I use comments in JSON?
No, JSON does not support comments. If you try to include a comment in your JSON data, it will result in a syntax error. If you need to include notes or comments in your JSON data, you can include them as string values with a specific key, such as “_comment”.
How can I handle large JSON files?
Handling large JSON files can be challenging due to memory limitations. One approach is to use a streaming JSON parser, which can read and process the JSON data in chunks, rather than loading the entire file into memory. Another approach is to use a database that supports JSON, such as MongoDB, which can efficiently store and query large amounts of JSON data.
Can I use JSON for configuration files?
Yes, JSON is often used for configuration files due to its simplicity and readability. However, keep in mind that JSON does not support comments, which can be a limitation for complex configuration files. Alternatives like YAML or TOML, which do support comments, might be more suitable for complex configurations.
How can I pretty-print JSON data?
Pretty-printing is the process of formatting JSON data in a way that is easy to read. This often involves adding indentation and line breaks. Many programming languages have built-in functions for pretty-printing JSON data. For example, in JavaScript, you can use JSON.stringify(data, null, 2)
to pretty-print JSON data with 2 spaces of indentation.
Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.