JSON Basics

From WikiMLT

JSON (JavaScript Ob­ject No­ta­tion) is a light­weight da­ta-in­ter­change for­mat. It is easy for hu­mans to read and write. It is easy for ma­chines to parse and gen­er­ate. It is based on a sub­set of the JavaScript Pro­gram­ming Lan­guage Stan­dard EC­MA-262 3rd Edi­tion – De­cem­ber 1999. JSON is a text for­mat that is com­plete­ly lan­guage in­de­pen­dent but us­es con­ven­tions that are fa­mil­iar to pro­gram­mers of the C‑family of lan­guages, in­clud­ing C, C++, C#, Ja­va, JavaScript, Perl, Python, and many oth­ers. These prop­er­ties make JSON an ide­al da­ta-in­ter­change lan­guage.

JSON is built on two struc­tures:

  • A col­lec­tion of name/​​​value pairs. In var­i­ous lan­guages, this is re­al­ized as an ob­ject, record, struct, dic­tio­nary, hash ta­ble, keyed list, or as­so­cia­tive ar­ray.
  • An or­dered list of val­ues. In most lan­guages, this is re­al­ized as an ar­ray, vec­tor, list, or se­quence.

These are uni­ver­sal da­ta struc­tures. Vir­tu­al­ly all mod­ern pro­gram­ming lan­guages sup­port them in one form or an­oth­er. It makes sense that a da­ta for­mat that is in­ter­change­able with pro­gram­ming lan­guages al­so be based on these struc­tures.

Ref­er­ences:

  • JSON​.org (nice graphs that ex­plain the JSON syn­tax).

JSON Ba­sic Syn­tax Rules

  • Use dou­ble quotes for keys and strings,
  • No lead­ing ze­roes in num­bers,
  • No trail­ing dec­i­mals in num­bers,
  • No trail­ing com­ma,
  • No com­ments.

Ba­sic ex­am­ple:

{
  "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"
    }
  }
}

Ref­er­ences:

Con­vert­ing to and from JSON

Se­ri­al­ize and dester­il­ize da­ta.

Lan­guage Util­i­ties
JavaScript JSON.parse('string');
JSON.stringify('js-object');
For­mat­ted with in­den­tion of 4 spaces at the con­sole (serv­er side): JSON.stringify('js-object', null, 4);
Python json.dimp and json.load
Ja­va org.json and GSON

JSON Schema

Figure 1. LinkedIn Learn­ing: JSON Es­sen­tial Train­ing [27/41] 5. Work­ing with JSON Schema 1. What is JSON Schema.

JSON Schema is a vo­cab­u­lary that al­lows you to an­no­tate and val­i­date JSON doc­u­ments.

Ben­e­fits:

  • De­scribes your ex­ist­ing da­ta format(s).
  • Pro­vides clear hu­man- and ma­chine- read­able doc­u­men­ta­tion.
  • Val­i­dates da­ta which is use­ful for:
    • Au­to­mat­ed test­ing.
    • En­sur­ing qual­i­ty of client sub­mit­ted da­ta.

Ref­er­ences:

JSON-LD

Figure 2. LinkedIn Learn­ing: JSON Es­sen­tial Train­ing [34/41] 6. Struc­tur­ing Da­ta with JSON-LD 1. What is JSON-LD.

JSON for Link­ing Da­ta. Ref: JSON​-LD​.org:

  • Linked Da­ta em­pow­ers peo­ple that pub­lish and use in­for­ma­tion on the Web. It is a way to cre­ate a net­work of stan­dards-based, ma­chine-read­able da­ta across Web sites. It al­lows an ap­pli­ca­tion to start at one piece of Linked Da­ta, and fol­low em­bed­ded links to oth­er pieces of Linked Da­ta that are host­ed on dif­fer­ent sites across the Web.
  • JSON-LD is a light­weight Linked Da­ta for­mat. It is easy for hu­mans to read and write. It is based on the al­ready suc­cess­ful JSON for­mat and pro­vides a way to help JSON da­ta in­ter­op­er­ate at Web-scale. JSON-LD is an ide­al da­ta for­mat for pro­gram­ming en­vi­ron­ments, REST Web ser­vices, and un­struc­tured data­bas­es such as Apache CouchDB and Mon­goDB.

Ex­am­ple:

{
  "@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 stan­dards – vo­cab­u­lar­ies. Schema​.org is de­fined as two hi­er­ar­chies: one for tex­tu­al prop­er­ty val­ues, and one for the things that they de­scribe – see the ar­ti­cle: Full Hi­er­ar­chy.

Ex­am­ple based on the Or­ga­ni­za­tion vo­cab­u­lary of Schema​.org – checked for syn­tax er­rors by the tool JSON​-LD​.org Play­ground:

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 Da­ta Struc­ture with JSON-LD. In­stead of re­nam­ing your JSON da­ta keys you can in­clude an ad­di­tion­al ob­ject in your JSON-LD snip­pet that map you key names to the key names used in a con­text and type that your snip­pet ref­er­ences.

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 pro­vide JSON-LD via an HTML file. This can helps search en­gines in­dex the page. The fol­low­ing ex­am­ple is gen­er­at­ed by Schema Markup (JSON-LD) Gen­er­a­tor.

<!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>

Ref­er­ences:

JSON Pre­vent da­ta reuse (XSS at­tack)

Cross Site Script­ing (XSS) at­tacks are a type of in­jec­tion, in which ma­li­cious scripts are in­ject­ed in­to oth­er­wise be­nign and trust­ed web­sites. XSS at­tacks oc­cur when an at­tack­er us­es a web ap­pli­ca­tion to send ma­li­cious code, gen­er­al­ly in the form of a brows­er side script, to a dif­fer­ent end user. Flaws that al­low these at­tacks to suc­ceed are quite wide­spread and oc­cur any­where a web ap­pli­ca­tion us­es in­put from a user with­in the out­put it gen­er­ates with­out val­i­dat­ing or en­cod­ing it.

Figure 3. LinkedIn Learn­ing: JSON Es­sen­tial Train­ing [24/41] 4. Ap­ply­ing Tech­niques for Work­ing with JSON 1. Pre­vent da­ta reuse: Pro­tect­ing against XS­SI at­tack.

An at­tack­er can use XSS to send a ma­li­cious script to an un­sus­pect­ing user. The end user’s brows­er has no way to know that the script should not be trust­ed, and will ex­e­cute the script. Be­cause it thinks the script came from a trust­ed source, the ma­li­cious script can ac­cess any cook­ies, ses­sion to­kens, or oth­er sen­si­tive in­for­ma­tion re­tained by the brows­er and used with that site. These scripts can even rewrite the con­tent of the HTML page. For more de­tails on the dif­fer­ent types of XSS flaws, see: Types of Cross-Site Script­ing.

Ref­er­ences and notes:

JSON‑P

JSON with Padding. JSONP is a method for send­ing JSON da­ta with­out wor­ry­ing about cross-do­main is­sues. JSONP does not use the XML­HttpRe­quest ob­ject. JSONP us­es the <script> tag in­stead. Ref: W3S JSONP.

Use CORS (Ac­cess-Con­trol-Al­low-Ori­gin) in­stead of JSON‑P.

Brows­er tools

Figure 4. JSON pret­ty for­mat tools: Chromi­um based Brave brows­er (left) Vs Fire­fox (right).

LinkedIn Learn­ing JSON Es­sen­tial Train­ing