JSON Basics
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.
References:
- JSON.org (nice graphs that explain the JSON syntax).
JSON Basic Syntax Rules
- Use double quotes for keys and strings,
- No leading zeroes in numbers,
- No trailing decimals in numbers,
- No trailing comma,
- No comments.
Basic example:
{
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
References:
Converting to and from JSON
Serialize and desterilize data.
Language | Utilities |
---|---|
JavaScript | JSON.parse('string'); JSON.stringify('js-object'); Formatted with indention of 4 spaces at the console (server side): JSON.stringify('js-object', null, 4);
|
Python | json.dimp and json.load
|
Java | org.json and GSON
|
JSON Schema
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.
Benefits:
- Describes your existing data format(s).
- Provides clear human- and machine- readable documentation.
- Validates data which is useful for:
- Automated testing.
- Ensuring quality of client submitted data.
References:
- JSON.Schema.org.
- JSON.Schema.org > Implementations > Validators.
- NPM: AJV – JSON schema validator (for backend use).
- Run it right into the browser: RunKit+NPM AJV | Lesson [33/41] from the LinkedIn's JSON Course.
- Generate JSON Schema from JSON by JsonSchema.net.
JSON-LD
JSON for Linking Data. Ref: JSON-LD.org:
- Linked Data empowers people that publish and use information on the Web. It is a way to create a network of standards-based, machine-readable data across Web sites. It allows an application to start at one piece of Linked Data, and follow embedded links to other pieces of Linked Data that are hosted on different sites across the Web.
- JSON-LD is a lightweight Linked Data format. It is easy for humans to read and write. It is based on the already successful JSON format and provides a way to help JSON data interoperate at Web-scale. JSON-LD is an ideal data format for programming environments, REST Web services, and unstructured databases such as Apache CouchDB and MongoDB.
Example:
{
"@context": "https://json-ld.org/contexts/person.jsonld",
"@id": "http://dbpedia.org/resource/John_Lennon",
"name": "John Lennon",
"born": "1940-10-09",
"spouse": "http://dbpedia.org/resource/Cynthia_Lennon"
}
Schema.org – one of the providers of such standards – vocabularies. Schema.org is defined as two hierarchies: one for textual property values, and one for the things that they describe – see the article: Full Hierarchy.
Example based on the Organization vocabulary of Schema.org – checked for syntax errors by the tool JSON-LD.org Playground:
snippet.jsonld
{
"@context": "https://schema.org/",
"@type": "Organization",
"name": "h+ Sport",
"url": "https://hplussport.com",
"logo": "https://hplussport.com/wp-content/uploads/2017/04/H-logo_470x271.png",
"description": "H+ Sport is dedicated to creating eco-friendly, high-quality, nutrient-rich, nutritional products that enhance active lifestyles. In addition, our H+ Sport Active clothing line is made to be functional, stylish, comfortable, and durable, using all natural and organic fibers."
}
snippet.json
{
"company": "h+ Sport",
"website": "https://hplussport.com",
"image": "https://hplussport.com/wp-content/uploads/2017/04/H-logo_470x271.png",
"overview": "H+ Sport is dedicated to creating eco-friendly, high-quality, nutrient-rich, nutritional products that enhance active lifestyles. In addition, our H+ Sport Active clothing line is made to be functional, stylish, comfortable, and durable, using all natural and organic fibers."
}
Map a Data Structure with JSON-LD. Instead of renaming your JSON data keys you can include an additional object in your JSON-LD snippet that map you key names to the key names used in a context and type that your snippet references.
snippet.jsonld # Example for Map
{
"@context": {
"@vocab": "https://www.schema.org/",
"company": "name",
"website": "url",
"image": "logo",
"overview": "description"
},
"@type": "Organization",
"company": "h+ Sport",
"website": "https://hplussport.com",
"image": "https://hplussport.com/wp-content/uploads/2017/04/H-logo_470x271.png",
"overview": "H+ Sport is dedicated to creating eco-friendly, high-quality, nutrient-rich, nutritional products that enhance active lifestyles. In addition, our H+ Sport Active clothing line is made to be functional, stylish, comfortable, and durable, using all natural and organic fibers."
}
snippet.json
{
"company": "h+ Sport",
"website": "https://hplussport.com",
"image": "https://hplussport.com/wp-content/uploads/2017/04/H-logo_470x271.png",
"overview": "H+ Sport is dedicated to creating eco-friendly, high-quality, nutrient-rich, nutritional products that enhance active lifestyles. In addition, our H+ Sport Active clothing line is made to be functional, stylish, comfortable, and durable, using all natural and organic fibers."
}
How to provide JSON-LD via an HTML file. This can helps search engines index the page. The following example is generated by Schema Markup (JSON-LD) Generator.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- rest of your code -->
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "Event",
"name": "",
"eventAttendanceMode": "https://schema.org/OnlineEventAttendanceMode",
"eventStatus": "https://schema.org/EventScheduled",
"startDate": "",
"location": [
{
"@type": "VirtualLocation",
"url": ""
}
]
}
</script>
</head>
<body>
<!-- rest of your code -->
</body>
</html>
References:
- The above examples are based on the materials provided in the LinkedIn's JSON Essential Training [36–40/41] 6. Structuring Data with JSON-LD 3. Map a data structure with JSON-LD.
- Search results for: JSON-LS Generators.
- Web code tools: Schema Markup (JSON-LD) Generator.
JSON Prevent data reuse (XSS attack)
Cross Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page. For more details on the different types of XSS flaws, see: Types of Cross-Site Scripting.
References and notes:
- Remember the
while(1)
trick in JS. - Test for empty response by
(Object.keys(data).length === 0 && data.constructor === Object)
in modern browsers or use(hasOwnProperty === true)
for backward compatibility. Ref: LinkedIn Learning JSON Essential Training 4.3.
JSON‑P
JSON with Padding. JSONP is a method for sending JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest
object. JSONP uses the <script>
tag instead. Ref: W3S JSONP.
Use CORS (Access-Control-Allow-Origin) instead of JSON‑P.
Browser tools
- JSON example API: https://hplussport.com/api/products.
- JSON/XML conversion tool: www.goessner.net/download/prj/jsonxml/ | Example by LinkedIn Learning.
LinkedIn Learning JSON Essential Training
- LinkedIn Learning: JSON Essential Training
- GitHub LinkedIn Learning: JSON Essential Training